Find All Anagrams in a String

Medium

Topics
StringHash TableSliding Window

Return the start index of every substring of s that is an anagram of t, in ascending order.

An anagram uses exactly the same letters with the same multiplicities, in any order. Substrings may overlap.

LeetCode names the second argument p; the harness here calls it t.

Example 1

sc0b1a2e3b4a5b6a7c8d9
tabc
answer06
covered by a matching windowthe pattern
Looking for abc inside cbaebabacd gives 2 matchs. Every candidate is a window of exactly 3 characters, and it qualifies when its letter counts match — so order inside the window is irrelevant but multiplicities are not. The matches here do not overlap, though overlapping ones would each be reported.
The answer is start indices into s, ascending.
Input:  s = "cbaebabacd", t = "abc"
Output: [0,6]
Explanation: The substring starting at 0 is "cba" and the one at 6 is "bac", both anagrams of "abc".

Example 2

sa0b1a2b3
tab
answer012
covered by a matching windowthe pattern
The matching windows here overlap, which is permitted; the answer reports each start index separately.
Input:  s = "abab", t = "ab"
Output: [0,1,2]
Explanation: "ab", "ba" and "ab" all qualify, and they overlap — overlapping is allowed.

Example 3

sa0
tab
answer
empty array
the pattern
Looking for ab inside a gives nothing. The pattern is longer than the text, so no window of that width exists at all.
Input:  s = "a", t = "ab"
Output: []
Explanation: t is longer than s, so no substring can match.

Constraints

  • 1 <= s.length, t.length <= 3 * 10^4
  • s and t consist of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every candidate is a substring of exactly len(t) characters, so there are only len(s) - len(t) + 1 of them and the question per candidate is whether its letter counts match t’s.

Counting each candidate from scratch is the obvious version and it redoes almost all the work: consecutive candidates share all but two characters. Instead keep the counts for the current window and update them as the window advances — add the letter entering on the right, drop the letter leaving on the left.

Comparing the two count tables after every step is 26 comparisons, which is a constant but a wasteful one. The trick worth knowing is to maintain a single number: how many of the 26 letters currently have a matching count. Adjust it only for the two letters that actually changed, and a window is an anagram exactly when that number is 26.

Note what an anagram is not: it is not a subsequence and not a set. "aab" and "abb" use the same letters and are not anagrams, so multiplicities have to be compared, not just presence.

Approach

  1. If t is longer than s, return an empty list.
  2. Count the letters of t, and count the letters of the first window of len(t) characters of s.
  3. Record how many of the 26 letters have equal counts in the two tables.
  4. Slide the window one position at a time. For the letter entering and the letter leaving, update its count and adjust the match tally only if that letter crossed into or out of agreement.
  5. Whenever the tally is 26, record the window’s start index.
  6. The indices are produced left to right, so they are already ascending.

Walkthrough

s = "abab", t = "ab"

t needs: a:1 b:1
window width 2

   window [0,1] = "ab"   a:1 b:1   MATCH -> record 0
   slide: drop s[0]="a", add s[2]="a"
   window [1,2] = "ba"   a:1 b:1   MATCH -> record 1
   slide: drop s[1]="b", add s[3]="b"
   window [2,3] = "ab"   a:1 b:1   MATCH -> record 2

answer [0, 1, 2]

the windows overlap, which the problem allows.

s = "cbaebabacd", t = "abc"
   width 3
   [0,2] "cba"  a:1 b:1 c:1   MATCH -> 0
   [1,3] "bae"  e present     no
   [2,4] "aeb"  e present     no
   [3,5] "eba"  e present     no
   [4,6] "bab"  a:1 b:2       no  <- same letters as "abb",
                                     not an anagram of "abc"
   [5,7] "aba"  a:2 b:1       no
   [6,8] "bac"  a:1 b:1 c:1   MATCH -> 6
   [7,9] "acd"  d present     no

answer [0, 6]

Complexity

  • Time — O(n): each character enters and leaves the window once, with a constant update each time.
  • Space — O(1): two tables of 26 counts, whatever the input length.

Common Pitfalls

  • Recounting the window from scratch at every position, which is correct and quadratic at thirty thousand characters.
  • Comparing sets of letters rather than counts, so "aab" wrongly matches "abb".
  • Forgetting the first window. The loop that slides starts at the second one, so index 0 has to be checked before it.
  • Returning [] only when t is longer is easy to miss, and indexing the first window then reads past the end of s.
  • Adjusting the match tally for every letter instead of only the two that changed, which is correct but defeats the point.

Full Solution — all languages

class Solution:
    def findAnagrams(self, s, t):
        if len(t) > len(s):
            return []

        need = [0] * 26
        have = [0] * 26
        base = ord("a")

        for ch in t:
            need[ord(ch) - base] += 1
        for ch in s[:len(t)]:
            have[ord(ch) - base] += 1

        matched = sum(1 for i in range(26) if need[i] == have[i])

        out = []
        if matched == 26:
            out.append(0)

        for i in range(len(t), len(s)):
            # Only two letters change, so only two can cross into or out of
            # agreement -- adjust the tally for those and nothing else.
            enter = ord(s[i]) - base
            have[enter] += 1
            if have[enter] == need[enter]:
                matched += 1
            elif have[enter] == need[enter] + 1:
                matched -= 1

            leave = ord(s[i - len(t)]) - base
            have[leave] -= 1
            if have[leave] == need[leave]:
                matched += 1
            elif have[leave] == need[leave] - 1:
                matched -= 1

            if matched == 26:
                out.append(i - len(t) + 1)

        return out
SensAI
Beta
Tap the mic to stop voice mode