LeetCode 438 - Find All Anagrams in a String
LeetCode 438 - Find All Anagrams in a String
Table of Contents
Problem Statement
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.
Using Sliding Window
Explanation
- Frequency Arrays:
count_pstores the character frequencies ofp.count_windowtracks the character frequencies in the current window ofs.
- Initialize the First Window:
- Process the first
p.length()characters ofsto initializecount_window. - Compare
count_windowwithcount_p—if they match, store the starting index (0).
- Process the first
- Sliding the Window:
- For every new character in
s(starting from indexp.length()), adjustcount_window:- Remove the character that is slides out of the window.
- Add the new character that slides into the window.
- After each adjustment, compare
count_windowandcount_p. If they match, store the current starting index.
- For every new character in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> result;
if (s.length() < p.length()) return result;
vector<int> count_p(26, 0);
vector<int> count_window(26, 0);
for (int i = 0; i < p.length(); i++) {
count_p[p[i] - 'a']++;
count_window[s[i] - 'a']++;
}
if (count_window == count_p) {
result.push_back(0);
}
for (int i = p.length(); i < s.length(); i++) {
count_window[s[i - p.length()] - 'a']--;
count_window[s[i] - 'a']++;
if (count_window == count_p) {
result.push_back(i - p.length() + 1);
}
}
return result;
}
};
Conclusion
- Time Complexity: 𝑂(𝑛) — Each character is processed once.
- Space Complexity: 𝑂(1) — The frequency arrays have a fixed size of 26, meaning constant space is used.