Find All Anagrams in a String
Given two strings s and p, find all start indices in s where a substring is an anagram of p. Return the indices in any order. An anagram is a rearrangement of characters with the same frequency.
A sliding window approach with a hash map solves this in O(n) time. Count character frequencies in p. Slide a window of length p over s, updating frequencies. When the window frequencies match p's frequencies, record the start index. The window slides by removing the leftmost character and adding the next character to the right.
This is a classic medium problem combining hash tables with the sliding window technique.
The sliding window approach maintains a dynamic window that expands and contracts. The match counter tracks how many characters in the current window satisfy the frequency requirement. When match = len(p), all characters match and the left pointer is recorded. This avoids comparing the entire frequency map at every position.
The sliding window approach runs in O(n) time where n is the length of s. The match counter is the key optimization: instead of comparing the entire frequency map at each position, we track how many characters currently satisfy the frequency requirement. This reduces each position check to O(1).
Example Input & Output
Anagrams at index 0 (cba) and 6 (bac).
No anagrams found.
Anagrams at 0 (ab), 1 (ba), 2 (ab).
Algorithm Flow

Solution Approach
Count target frequencies in p. Use two pointers as a sliding window. Maintain a match count. When match equals map size, record left index.
Time O(n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public List<Integer> solution(String s, String p) {
List<Integer> result = new ArrayList<>();
int[] need = new int[26];
for (char ch : p.toCharArray()) need[ch-'a']++;
int left = 0, match = 0;
for (int right = 0; right < s.length(); right++) {
int idx = s.charAt(right) - 'a';
if (--need[idx] >= 0) match++;
if (right - left + 1 > p.length()) {
int lidx = s.charAt(left) - 'a';
if (++need[lidx] > 0) match--;
left++;
}
if (match == p.length()) result.add(left);
}
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
