Problem Description
Given two strings s and p, return an array of all start indices of p's anagrams in s. An anagram of p is any permutation of the characters in p. The order of the returned indices does not matter.
Key Insights
- Use a sliding window of length equal to p over s.
- Maintain frequency counts of characters in p and within the current window in s.
- Compare frequency counts to determine if the current window is an anagram.
- Update the window efficiently by adding one character and removing the character that goes out of the window.
Space and Time Complexity
Time Complexity: O(n) where n is the length of s. Space Complexity: O(1) since we use fixed-size frequency arrays or hash maps.
Solution
We use the sliding window technique to iterate over s with a window size equal to the length of p. First, count the frequencies of characters in p. Then, iterate over s and update a frequency count for the current window. When the window size equals the length of p, compare the two frequency counts. If they match, record the start index. To slide the window efficiently, increment the count for the incoming character and decrement the count for the outgoing character. This way, we achieve an O(n) solution that is optimal for the problem constraints.