📖 4 min read
Last updated on

Find All Anagrams in a String — Coding Interview Walkthrough


Hero Image for Find All Anagrams in a String — Coding Interview Walkthrough

You’re in a coding interview. The interviewer says: “Find all start indices of anagrams of p in s.” This is a fixed-size sliding window with character frequency comparison. As the window slides, you add the incoming character and remove the outgoing one, then check if counts match.


Already know how to solve Find All Anagrams In A String? Try a Find All Anagrams In A String mock interview on Intervu →

The Problem

Given two strings s and p, return a list of all start indices of p’s anagrams in s.

Example

Input: s = "cbaebabacd", p = "abc" Output: [0, 6]


What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Fixed-size sliding windowDo you slide a window of size len(p) across s?
Efficient comparisonDo you use a matches counter for O(1) per step?
Add-and-removeDo you increment/decrement counts correctly?

Step 1: The Key Insight

A fixed-size sliding window of length len(p). Track a matches counter — the number of characters (out of 26) whose counts currently agree between the window and p. When matches == 26, the window is an anagram.

String 'cbaebabacd' with fixed-size sliding window of length 3 highlighted at positions 0-2, showing anagram match 'cba' of pattern 'abc'. ---

Python Implementation

def findAnagrams(s: str, p: str) -> list[int]:
    if len(p) > len(s):
        return []

    p_count = [0] * 26
    s_count = [0] * 26

    for c in p:
        p_count[ord(c) - ord('a')] += 1
    for c in s[:len(p)]:
        s_count[ord(c) - ord('a')] += 1

    matches = sum(1 for i in range(26) if p_count[i] == s_count[i])
    result = [0] if matches == 26 else []

    for i in range(len(p), len(s)):
        incoming = ord(s[i]) - ord('a')
        outgoing = ord(s[i - len(p)]) - ord('a')

        s_count[incoming] += 1
        if s_count[incoming] == p_count[incoming]:
            matches += 1
        elif s_count[incoming] == p_count[incoming] + 1:
            matches -= 1

        s_count[outgoing] -= 1
        if s_count[outgoing] == p_count[outgoing]:
            matches += 1
        elif s_count[outgoing] == p_count[outgoing] - 1:
            matches -= 1

        if matches == 26:
            result.append(i - len(p) + 1)

    return result

Time & Space Complexity

AspectComplexity
TimeO(n) — O(1) per step
SpaceO(1) — two 26-element arrays

Common Interview Mistakes

  1. Recomputing frequency counts from scratch each window — O(n × L) instead of O(n).
  2. Not deleting zero-count entries in Counter comparisons — breaks equality.
  3. Off-by-one in start index. Window ending at i starts at i - len(p) + 1.

What a Strong Candidate Sounds Like

“Fixed-size sliding window of length len(p). I track a matches variable — how many of the 26 characters have equal counts. When I slide, I update two counts and adjust matches. When matches == 26, it’s an anagram. O(1) per step, O(n) total.”



Frequently Asked Questions

What is the optimal algorithmic pattern for finding anagrams in a string?

The most optimal solution uses the Sliding Window pattern alongside a frequency hash map. By creating a fixed-size window matching the target string length, you can slide across the sequence, incrementally adjusting character counts in O(1) time at each step instead of evaluating the whole substring.

The optimal algorithm runs in O(N) time where N is the length of the string being searched. Updating the frequency map and evaluating anagram validity evaluates constantly in O(1) time at each character step, completely dodging nested iterations.

Practice This in a Mock Interview

Start a mock interview for Find All Anagrams in a String on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →