Algo-Sim › Sliding Window
Find All Anagrams in a String
Medium · Sliding Window · step through it in Java, Python and C++ on your own input
Slide a window of length |p| over s and record every start where the window holds exactly the letters of p.
Problem
Given strings s and p, return the start index of every substring of s that is a rearrangement of all the letters of p. The indices may be returned in any order.
Constraints
- 1 ≤ s.length, p.length ≤ 3 · 10⁴
- Both strings contain only lowercase English letters
Edge cases to test
- p longer than s: no answers
- Overlapping matches:
"abab", p ="ab" - Repeated letters in p
Follow-up questions
- What if p is long and the alphabet is huge?
- Keep the window as a hash-map difference and a count of keys that are off by non-zero: O(1) per slide, O(distinct) space.
- How would rolling hashes help?
- Hash the multiset of letters (a sum of per-letter random values) to compare windows in O(1), then confirm hits: Rabin–Karp-style.
Solution
Java
public List<Integer> findAnagrams(String s, String p) {
List<Integer> starts = new ArrayList<>();
int[] count = new int[26];
for (char c : p.toCharArray()) count[c - 'a']++;
int m = p.length(), missing = m;
for (int right = 0; right < s.length(); right++) {
if (right >= m) {
int out = s.charAt(right - m) - 'a';
if (++count[out] > 0) missing++;
}
int in = s.charAt(right) - 'a';
if (count[in]-- > 0) missing--;
if (missing == 0) {
starts.add(right - m + 1);
}
}
return starts;
}Python
def find_anagrams(s, p):
starts, count = [], [0] * 26
for ch in p: count[ord(ch) - 97] += 1
m = missing = len(p)
for right in range(len(s)):
if right >= m:
out = ord(s[right - m]) - 97
count[out] += 1
if count[out] > 0: missing += 1
c = ord(s[right]) - 97
if count[c] > 0: missing -= 1
count[c] -= 1
if missing == 0:
starts.append(right - m + 1)
return startsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> findAnagrams(string &s, string &p) {
vector<int> starts;
vector<int> count = vector<int>(26);
for (char c : p)
count[c - 'a']++;
int m = int(p.size()), missing = m;
for (int right = 0; right < int(s.size()); right++) {
if (right >= m) {
int out = s[right - m] - 'a';
if (++count[out] > 0)
missing++;
}
int in = s[right] - 'a';
if (count[in]-- > 0)
missing--;
if (missing == 0) {
starts.push_back(right - m + 1);
}
}
return starts;
}
};
More Sliding Window problems
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)