Practice › Sliding Window
Count Anagram Occurrences
Easy · Sliding Window · Asked at Amazon, Microsoft, Meta, TCS, Infosys
Print how many substrings of text (at different starting positions) are anagrams of pattern — i.e. use exactly the same letters with the same counts.
Input
Two lines: text, then pattern (lowercase letters).
Output
The number of anagram occurrences.
Constraints
- 1 ≤ |pattern| ≤ |text| ≤ 10^5
Slide a window of length |pattern| over the text, keeping letter counts. Instead of comparing all 26 counts each step, keep the number of letters whose counts currently match and update it as one letter enters and one leaves.
Example 1
Input
forxxorfxdofr for
Output
3
Example 2
Input
aabaabaa aaba
Output
4
Hints
- An anagram of the pattern is a window of the same length with the same letter counts.
- Slide a fixed window: one letter enters, one leaves.
- Track how many of the 26 letters currently have the right count, so each step is O(1).
Approach
Let need[] be the pattern's counts and have[] the window's. Keep matches = number of letters c with have[c] == need[c]; with an empty window that is the number of letters absent from the pattern. When a letter enters or leaves, update matches only for that letter: before changing, if it matched, matches−−; after changing, if it matches, matches++. Whenever the window is full and matches == 26, count one occurrence.
Complexity: O(|text| + 26) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int needc[26], havec[26], matches = 26;
void change(int c, int d) {
if (havec[c] == needc[c]) matches--;
havec[c] += d;
if (havec[c] == needc[c]) matches++;
}
int main() {
string t, p;
cin >> t >> p;
for (char c : p) needc[c - 'a']++;
matches = 0;
for (int c = 0; c < 26; c++) matches += (needc[c] == 0);
int k = p.size(), count = 0;
for (int i = 0; i < (int) t.size(); i++) {
change(t[i] - 'a', 1);
if (i >= k) change(t[i - k] - 'a', -1);
if (i >= k - 1 && matches == 26) count++;
}
cout << count << "\n";
return 0;
}Python solution
import sys
t, p = sys.stdin.read().split()[:2]
k = len(p)
need = [0] * 26
for c in p:
need[ord(c) - 97] += 1
have = [0] * 26
matches = sum(1 for c in range(26) if need[c] == 0)
def change(c, d):
global matches
if have[c] == need[c]:
matches -= 1
have[c] += d
if have[c] == need[c]:
matches += 1
count = 0
for i, ch in enumerate(t):
change(ord(ch) - 97, 1)
if i >= k:
change(ord(t[i - k]) - 97, -1)
if i >= k - 1 and matches == 26:
count += 1
print(count)Java solution
import java.io.*;
public class Main {
static int[] need = new int[26], have = new int[26];
static int matches;
static void change(int c, int d) {
if (have[c] == need[c]) matches--;
have[c] += d;
if (have[c] == need[c]) matches++;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String t = br.readLine().trim(), p = br.readLine().trim();
for (char c : p.toCharArray()) need[c - 'a']++;
for (int c = 0; c < 26; c++) if (need[c] == 0) matches++;
int k = p.length(), count = 0;
for (int i = 0; i < t.length(); i++) {
change(t.charAt(i) - 'a', 1);
if (i >= k) change(t.charAt(i - k) - 'a', -1);
if (i >= k - 1 && matches == 26) count++;
}
System.out.println(count);
}
}Solve Count Anagram Occurrences online · All practice problems