Find All Anagrams in a String
Medium
Topics
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
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.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
Input: s = "abab", t = "ab" Output: [0,1,2] Explanation: "ab", "ba" and "ab" all qualify, and they overlap — overlapping is allowed.
Example 3
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
- If
tis longer thans, return an empty list. - Count the letters of
t, and count the letters of the first window oflen(t)characters ofs. - Record how many of the 26 letters have equal counts in the two tables.
- 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.
- Whenever the tally is 26, record the window’s start index.
- 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 whentis longer is easy to miss, and indexing the first window then reads past the end ofs. - 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 outimport java.util.*;
class Solution {
public List<Integer> findAnagrams(String s, String t) {
int n = s.length(), m = t.length();
List<Integer> out = new ArrayList<>();
if (m > n) return out;
int[] need = new int[26], have = new int[26];
for (int i = 0; i < m; i++) need[t.charAt(i) - 'a']++;
for (int i = 0; i < m; i++) have[s.charAt(i) - 'a']++;
int matched = 0;
for (int i = 0; i < 26; i++) if (need[i] == have[i]) matched++;
if (matched == 26) out.add(0);
for (int i = m; i < n; i++) {
int enter = s.charAt(i) - 'a';
have[enter]++;
if (have[enter] == need[enter]) matched++;
else if (have[enter] == need[enter] + 1) matched--;
int leave = s.charAt(i - m) - 'a';
have[leave]--;
if (have[leave] == need[leave]) matched++;
else if (have[leave] == need[leave] - 1) matched--;
if (matched == 26) out.add(i - m + 1);
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> findAnagrams(string s, string t) {
int n = (int)s.size(), m = (int)t.size();
if (m > n) return {
};
vector<int> need(26, 0), have(26, 0);
for (char ch : t) need[ch - 'a']++;
for (int i = 0; i < m; i++) have[s[i] - 'a']++;
int matched = 0;
for (int i = 0; i < 26; i++) if (need[i] == have[i]) matched++;
vector<int> out;
if (matched == 26) out.push_back(0);
for (int i = m; i < n; i++) {
int enter = s[i] - 'a';
have[enter]++;
if (have[enter] == need[enter]) matched++;
else if (have[enter] == need[enter] + 1) matched--;
int leave = s[i - m] - 'a';
have[leave]--;
if (have[leave] == need[leave]) matched++;
else if (have[leave] == need[leave] - 1) matched--;
if (matched == 26) out.push_back(i - m + 1);
}
return out;
}
};/**
* @param {string} s
* @param {string} t
* @return {number[]}
*/ var findAnagrams = function(s, t) {
const n = s.length, m = t.length;
if (m > n) return [];
const need = new Array(26).fill(0);
const have = new Array(26).fill(0);
const base = 97;
for (const ch of t) need[ch.charCodeAt(0) - base]++;
for (let i = 0; i < m; i++) have[s.charCodeAt(i) - base]++;
let matched = 0;
for (let i = 0; i < 26; i++) if (need[i] === have[i]) matched++;
const out = [];
if (matched === 26) out.push(0);
for (let i = m; i < n; i++) {
const enter = s.charCodeAt(i) - base;
have[enter]++;
if (have[enter] === need[enter]) matched++;
else if (have[enter] === need[enter] + 1) matched--;
const leave = s.charCodeAt(i - m) - base;
have[leave]--;
if (have[leave] === need[leave]) matched++;
else if (have[leave] === need[leave] - 1) matched--;
if (matched === 26) out.push(i - m + 1);
}
return out;
};