15% off all plans & roadmaps Use code

See plans

Find All Anagrams in a String

Updated

TL;DR: Return every start index where a window of s, the same length as p, has the same letter counts as p. Slide one window across s and update a 26-slot count array in constant time per step.

Problem

Given two strings s and p, return every start index where an anagram of p begins in s. The answer can be in any order.

Example 1

Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation: Starting at index 0 gives "cba", an anagram of "abc". Starting at index 6 gives "bac", also an anagram of "abc".

Example 2

Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation: Starting at index 0 gives "ab", starting at index 1 gives "ba", and starting at index 2 gives "ab". Each is an anagram of "ab".

Constraints

  • 1 <= s.length, p.length <= 3 * 10^4
  • s and p consist of lowercase English letters.

Constraints that matter

  • n up to 3 * 10^4 rules out sorting every window when m is also large. With m near n / 2, the sort-per-window approach needs about 3 * 10^9 comparisons.
  • Both strings hold lowercase letters only, so one 26-slot count array covers every window. Comparing two such arrays costs constant time.
  • Every window has the same length m, so each step removes exactly one letter and adds exactly one letter. That makes an O(1) update per step possible.
  • The answer can hold up to n - m + 1 indices, so O(n) is the floor for any correct method in the worst case.

View on LeetCode

Hints

Hint 1

Two strings are anagrams when they contain the same letters with the same counts.

Hint 2

The brute force takes every window of length m and sorts its letters.

Solution

Intuition

Two strings are anagrams when they contain the same letters with the same counts. Order does not matter, so the question is about counts. A window matches when its letter counts equal the counts of p.

Picture a fixed-width frame sliding along a row of letter tiles. The count array is a tally sheet for the tiles inside the frame, and each move swaps one tile out and one tile in.

Every window has length m, the length of p. Moving from one window to the next changes only two positions. One letter leaves at the left edge and one letter enters at the right edge. This fixed-size sliding window is the pattern here, and the check is character frequency matching.

Recounting a window costs O(m) each time, which repeats almost all of the previous work. Updating two counts costs O(1). That update is the core of the optimal approach.

Watch the pattern animation

Worked example

Input: s = "aaabaaaabaa", p = "aab"
Output: [1, 2, 3, 6, 7, 8]
Explanation: Each window has length 3. Windows starting at 1, 2, 3, 6, 7 and 8 contain two a's and one b, which matches p. The windows at 0, 4 and 5 are all a's, so they fail.

Approach 1: Brute force with sorting

The brute force takes every window of length m and sorts its letters. Two strings are anagrams exactly when their sorted forms are equal, so the test is correct.

The waste is in the sorting. Neighbouring windows share m - 1 letters, yet each window is copied and sorted from scratch. That means n - m + 1 separate sorts.

Steps

  1. Sort the letters of p and store the sorted string.
  2. Loop i from 0 to n - m, the last valid start index.
  3. Copy s[i .. i + m - 1] and sort the copy.
  4. If the sorted copy equals sorted p, add i to the result.
  5. Return the result list.

Dry run

Sorted p is aab. Each window is sorted and compared:

  • i = 0, window aaa, sorted aaa, no match.
  • i = 1, window aab, sorted aab, match, record 1.
  • i = 2, window aba, sorted aab, match, record 2.
  • i = 3, window baa, sorted aab, match, record 3.
  • i = 4, window aaa, no match.
  • i = 5, window aaa, no match.
  • i = 6, window aab, match, record 6.
  • i = 7, window aba, match, record 7.
  • i = 8, window baa, match, record 8.

The result is [1, 2, 3, 6, 7, 8], which matches the expected output.

Complexity

TimeO(n * m log m)
SpaceO(m)

Let n be the length of s and m the length of p. The loop runs n - m + 1 times, and each pass copies and sorts a window of length m. Sorting m letters takes O(m log m) comparisons, so the loop costs O((n - m + 1) * m log m), which is O(n * m log m) in the worst case. The copied window and the sorted p take O(m) space, and the output list is not counted.

PythonTested in our runner

from typing import List

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        n, m = len(s), len(p)
        target = sorted(p)
        result = []
        for i in range(n - m + 1):
            # Sort the window and compare it with the sorted p
            if sorted(s[i:i + m]) == target:
                result.append(i)
        return result

The Character Frequency Matching infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Character Frequency Matching

Part of Sliding Window

Approach 2: One-pass sliding window with letter countsOptimalCharacter Frequency Matching

What is slow in the brute force is that each window is rebuilt from nothing. Neighbouring windows differ by one letter on each side, so almost all of the counts carry over. Keep one count array for the current window and update it as the window moves.

Adding the entering letter and removing the leaving letter each cost O(1). Then compare the window counts with the counts of p. Comparing two arrays of 26 integers takes constant time, so each step is O(1) work.

Why it is correct. After each step, the count array holds the exact letter counts of the current window, because every step adds the entering letter and removes the leaving one. Every window of length m is checked exactly once, so no matching start index is skipped or reported twice.

Steps

  1. Count the letters of p into the array need, with 26 slots for a through z.
  2. If m is greater than n, return an empty list.
  3. Walk i from 0 to n - 1. Add s[i] to the array have.
  4. If i is at least m, remove s[i - m] from have, since that letter has left the window.
  5. If i is at least m - 1, the window is full. When have equals need, add i - m + 1 to the result.
  6. Return the result list.

Dry run

The table traces the full run on the example. Each row is one loop step. The window is full from i = 2 onward, and a match needs a = 2 and b = 1, the counts of p.

Step iAddRemoveWindowabMatchResult
0anonea10not full[]
1anoneaa20not full[]
2anoneaaa30no[]
3bs[0] = aaab21yes[1]
4as[1] = aaba21yes[1, 2]
5as[2] = abaa21yes[1, 2, 3]
6as[3] = baaa30no[1, 2, 3]
7as[4] = aaaa30no[1, 2, 3]
8bs[5] = aaab21yes[1, 2, 3, 6]
9as[6] = aaba21yes[1, 2, 3, 6, 7]
10as[7] = abaa21yes[1, 2, 3, 6, 7, 8]

The final result is [1, 2, 3, 6, 7, 8], which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of s and m the length of p. Filling need takes O(m) work, and the main loop runs n times. Each step does at most two count updates and one comparison of two 26-slot arrays, all O(1). The total time is O(m + n), which is O(n) since m is at most n. The two count arrays hold 26 integers each, so the extra space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        n, m = len(s), len(p)
        result = []
        if m > n:
            return result
        need = [0] * 26
        have = [0] * 26
        for c in p:
            need[ord(c) - 97] += 1
        for i in range(n):
            # Add the entering letter
            have[ord(s[i]) - 97] += 1
            # Remove the letter that left the window
            if i >= m:
                have[ord(s[i - m]) - 97] -= 1
            if i >= m - 1 and have == need:
                result.append(i - m + 1)
        return result

Common mistakes

  • Slicing s[i:i + m] and sorting or counting the slice inside the loop. Each slice costs O(m), so the pass becomes O(n * m). Update the counts in place instead.
  • Removing s[i] instead of s[i - m]. The letter that leaves is m positions behind the new one. Removing the current letter drops a letter that is still in the window, and every later count drifts.
  • Recording i instead of i - m + 1. The loop index marks the end of the window, so the start index is m - 1 positions earlier.
  • Comparing counts before the window is full. For i below m - 1, the window holds fewer than m letters, so a short window can record a false match. Check only when i is at least m - 1.
  • Comparing arrays with the wrong equality check. Java == on arrays compares references, so equal contents return false. Use Arrays.equals in Java and element-wise comparison in JavaScript.
  • Skipping the m > n guard. Some solutions read the first m letters of s before checking lengths. When s is shorter than p, that read runs past the end of the string.

Edge cases

  • p longer than s, for example s = "ab" and p = "abc". Return an empty list, since no window of length 3 exists.
  • p equal to s, for example s = "abc" and p = "cba". Return [0], because the whole string is one window.
  • A single letter that matches, s = "a" and p = "a". Return [0]. With p = "b" instead, return [].
  • Repeated letters, s = "aaaaa" and p = "aa". Every start from 0 to 3 matches, so return [0, 1, 2, 3].
  • Maximum size, n = 30000 and m = 1. Each position is checked once, so the run is linear and the answer lists every position whose letter equals p.

Follow-ups interviewers ask

What if the alphabet is larger than lowercase letters, such as Unicode?
Replace the 26-slot arrays with a hash map of counts. Keep a counter of letters whose window count differs from the p count. Each add or remove changes that counter in O(1), so the check per step is O(1) instead of a full comparison. Expected time stays O(n) with hashing.
Can you do it in O(1) extra space?
The version above already uses O(1) extra space, because the arrays hold 26 numbers no matter how long s is. The result list is the output, not working memory, so it is not counted. If the alphabet were unbounded, the counts would need O(m) space.
What if s does not fit in memory and arrives as a stream?
The window must know which letter leaves, so you need the last m letters of the stream. Store them in a queue of length m, along with the two count arrays. That uses O(m) memory and O(n) time, which helps when p is short. If m is large, the buffer is large too.

Find All Anagrams in a String FAQ

What is the time complexity of Find All Anagrams in a String?

The optimal solution runs in O(n) time, where n is the length of s, because each step does constant work. The brute force that sorts every window takes O(n * m log m) time instead.

Why use a sliding window for Find All Anagrams in a String?

Every candidate is a window of length m, and consecutive windows differ by one letter on each side. A sliding window updates the counts for that change in O(1), so the earlier work carries over. Recounting each window would repeat almost all of it.

Can Find All Anagrams in a String be solved in O(1) extra space?

Yes. The working state is two arrays of 26 counts, which is constant space. The output list grows with the number of matches, but that list is the answer itself.

Does the order of letters in p matter?

No. Anagrams have the same letters with the same counts, so order is irrelevant. A window such as bca matches p equal to abc, because both contain one a, one b and one c.

Why compare count arrays instead of comparing strings?

Comparing strings needs each window to be sorted or rebuilt, which costs O(m) per step. The count arrays change by two updates per step, so comparing 26 numbers stays constant.

Asked at

See which companies ask this — Pro

Practise it