Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
Example 1:
Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s = "abab", p = "ab" Output: [0,1,2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab".
Constraints:
1 <= s.length, p.length <= 3 * 104s and p consist of lowercase English letters.Problem summary: Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"cbaebabacd" "abc"
"abab" "ab"
valid-anagram)permutation-in-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #438: Find All Anagrams in a String
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int m = s.length(), n = p.length();
List<Integer> ans = new ArrayList<>();
if (m < n) {
return ans;
}
int[] cnt1 = new int[26];
for (int i = 0; i < n; ++i) {
++cnt1[p.charAt(i) - 'a'];
}
int[] cnt2 = new int[26];
for (int i = 0; i < n - 1; ++i) {
++cnt2[s.charAt(i) - 'a'];
}
for (int i = n - 1; i < m; ++i) {
++cnt2[s.charAt(i) - 'a'];
if (Arrays.equals(cnt1, cnt2)) {
ans.add(i - n + 1);
}
--cnt2[s.charAt(i - n + 1) - 'a'];
}
return ans;
}
}
// Accepted solution for LeetCode #438: Find All Anagrams in a String
func findAnagrams(s string, p string) (ans []int) {
m, n := len(s), len(p)
if m < n {
return
}
cnt1 := [26]int{}
cnt2 := [26]int{}
for _, c := range p {
cnt1[c-'a']++
}
for _, c := range s[:n-1] {
cnt2[c-'a']++
}
for i := n - 1; i < m; i++ {
cnt2[s[i]-'a']++
if cnt1 == cnt2 {
ans = append(ans, i-n+1)
}
cnt2[s[i-n+1]-'a']--
}
return
}
# Accepted solution for LeetCode #438: Find All Anagrams in a String
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
m, n = len(s), len(p)
ans = []
if m < n:
return ans
cnt1 = Counter(p)
cnt2 = Counter(s[: n - 1])
for i in range(n - 1, m):
cnt2[s[i]] += 1
if cnt1 == cnt2:
ans.append(i - n + 1)
cnt2[s[i - n + 1]] -= 1
return ans
// Accepted solution for LeetCode #438: Find All Anagrams in a String
impl Solution {
pub fn find_anagrams(s: String, p: String) -> Vec<i32> {
let (s, p) = (s.as_bytes(), p.as_bytes());
let (m, n) = (s.len(), p.len());
let mut ans = vec![];
if m < n {
return ans;
}
let mut cnt = [0; 26];
for i in 0..n {
cnt[(p[i] - b'a') as usize] += 1;
cnt[(s[i] - b'a') as usize] -= 1;
}
for i in n..m {
if cnt.iter().all(|&v| v == 0) {
ans.push((i - n) as i32);
}
cnt[(s[i] - b'a') as usize] -= 1;
cnt[(s[i - n] - b'a') as usize] += 1;
}
if cnt.iter().all(|&v| v == 0) {
ans.push((m - n) as i32);
}
ans
}
}
// Accepted solution for LeetCode #438: Find All Anagrams in a String
function findAnagrams(s: string, p: string): number[] {
const m = s.length;
const n = p.length;
const ans: number[] = [];
if (m < n) {
return ans;
}
const cnt1: number[] = new Array(26).fill(0);
const cnt2: number[] = new Array(26).fill(0);
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
for (const c of p) {
++cnt1[idx(c)];
}
for (const c of s.slice(0, n - 1)) {
++cnt2[idx(c)];
}
for (let i = n - 1; i < m; ++i) {
++cnt2[idx(s[i])];
if (cnt1.toString() === cnt2.toString()) {
ans.push(i - n + 1);
}
--cnt2[idx(s[i - n + 1])];
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.