Windows with a count map
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many substring problems ask whether a window contains the exact multiset of characters of a target string p (anagrams/permutations) or at least the character counts of t (Minimum Window Substring). Pairing a sliding window with a frequency table and a single satisfied counter solves all of these in linear time.
Find all anagrams and Permutation in a string
Two strings are anagrams (or permutations of each other) when they have the same length and identical character frequencies.
Example 1 · Brute force: sort every window and compare (O(n · k log k) time, O(k) space)
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class FindAnagramsBrute { public static List<Integer> findAnagrams(String s, String p) { List<Integer> indices = new ArrayList<>(); int k = p.length(); char[] target = p.toCharArray(); Arrays.sort(target); for (int start = 0; start + k <= s.length(); start++) { char[] window = s.substring(start, start + k).toCharArray(); Arrays.sort(window); if (Arrays.equals(window, target)) { indices.add(start); } } return indices; }
public static void main(String[] args) { System.out.println("Anagrams of abc in cbaebabacd: " + findAnagrams("cbaebabacd", "abc")); }}Anagrams of abc in cbaebabacd: [0, 6]
What this code does
- Each window is copied, sorted and compared with the sorted pattern: n windows, each costing about k log k.
- Two strings are anagrams when their letter counts match. Counts can be kept for the window and updated in O(1) as it slides.
Example 2 · Optimal: fixed window with two count arrays (O(n) time, O(1) space)
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class FindAnagramsDemo { public static List<Integer> findAnagrams(String s, String p) { List<Integer> indices = new ArrayList<>(); int k = p.length(); if (s.length() < k) { return indices; } int[] need = new int[26]; int[] win = new int[26]; for (int i = 0; i < k; i++) { need[p.charAt(i) - 'a']++; } for (int right = 0; right < s.length(); right++) { win[s.charAt(right) - 'a']++; if (right >= k) { win[s.charAt(right - k) - 'a']--; } if (right >= k - 1 && Arrays.equals(need, win)) { indices.add(right - k + 1); } } return indices; }
public static boolean checkInclusion(String p, String s) { return !findAnagrams(s, p).isEmpty(); }
public static void main(String[] args) { System.out.println("Anagrams of abc in cbaebabacd: " + findAnagrams("cbaebabacd", "abc")); System.out.println("eidbaooo has permutation of ab: " + checkInclusion("ab", "eidbaooo")); }}Anagrams of abc in cbaebabacd: [0, 6] eidbaooo has permutation of ab: true
What this code does
- In "cbaebabacd", index 0 ("cba") and index 6 ("bac") have the exact same letter counts as "abc".
- Permutation in String (checkInclusion) is the exact same problem, returning true as soon as one match is found.
- Why it is faster: the window counts change by one letter in and one letter out, and comparing two arrays of 26 numbers is a constant cost, so no window is sorted.
Two problems follow from this:
- Permutation in a string: Does
scontain any substring that is a permutation ofp? - Find all anagrams in a string: Return all start indices of
s's substrings that are anagrams ofp.
Both are fixed-size window problems with window length k = p.length()! For lowercase English letters, we can maintain int[] need = new int[26] and int[] window = new int[26]. After sliding each step of size k, comparing Arrays.equals(need, window) takes 26 operations (O(1)), giving O(26 · n) = O(n) total time.
- If s.length() < p.length(), no anagram or permutation can exist.
- Fixed window size is k = p.length(): add s.charAt(right), and when right >= k subtract s.charAt(right - k).
- When right >= k - 1, if Arrays.equals(need, window) is true, record start index right - k + 1.
Tracking how many characters are satisfied
satisfied counts how many distinct required characters currently meet their requirement, so checking the whole window never needs a scan of the map, even for a large alphabet (full Unicode or arbitrary integers in a HashMap).
int[] need = new int[128], window = new int[128];for (char ch : "abc".toCharArray()) need[ch]++;int required = 3, satisfied = 0;
char c = 'a'; // 'a' enters the windowif (++window[c] == need[c]) satisfied++; // just became met: satisfied = 1
char d = 'a'; // 'a' leaves the windowif (window[d]-- == need[d]) satisfied--; // just became unmet: satisfied = 0
boolean valid = satisfied == required; // one comparison, no scanIt works with two integers:
required: the number of distinct characters in the target stringt(withneed[c] > 0).satisfied(orformed): how many of those distinct characters currently havewindow[c] >= need[c](for covering windows) orwindow[c] == need[c](for exact anagram windows).
When c enters the window and ++window[c] == need[c], that character just crossed the threshold from unmet to met, so we increment satisfied++. When d leaves the window and window[d]-- == need[d], that character just dropped below its requirement, so we decrement satisfied--. Checking whether the entire window is valid is now a single integer comparison: satisfied == required!
Minimum window substring
In Minimum Window Substring, given strings s and t, we want the shortest substring of s that contains every character of t (including duplicate counts), or "" if none exists.
- Populate need[128] from t and count distinct characters with need[c] > 0 as required.
- Expand right: window[c]++; if need[c] > 0 && window[c] == need[c], satisfied++.
- While satisfied == required: update bestStart and minLen, then remove out = s.charAt(left++) and if need[out] > 0 && window[out] == need[out], satisfied--; window[out]--.
- Return minLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + minLen).
Example 3 · Minimum Window Substring in O(|s| + |t|) using satisfied == required
public class MinWindowSubstringDemo { public static String minWindow(String s, String t) { if (s.length() < t.length()) { return ""; } int[] need = new int[128]; int required = 0; for (int i = 0; i < t.length(); i++) { char c = t.charAt(i); if (need[c] == 0) { required++; } need[c]++; }
int[] window = new int[128]; int left = 0, satisfied = 0; int bestStart = 0, minLen = Integer.MAX_VALUE;
for (int right = 0; right < s.length(); right++) { char c = s.charAt(right); window[c]++; if (need[c] > 0 && window[c] == need[c]) { satisfied++; } while (satisfied == required) { int len = right - left + 1; if (len < minLen) { minLen = len; bestStart = left; } char out = s.charAt(left++); if (need[out] > 0 && window[out] == need[out]) { satisfied--; } window[out]--; } } return minLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + minLen); }
public static void main(String[] args) { System.out.println("Min window(ADOBECODEBANC, ABC): " + minWindow("ADOBECODEBANC", "ABC")); System.out.println("Min window(aa, aa): " + minWindow("aa", "aa")); }}Min window(ADOBECODEBANC, ABC): BANC Min window(aa, aa): aa
What this code does
- For t = "aa", required is 1 (one distinct character 'a' with need['a'] == 2). satisfied only becomes 1 when window['a'] reaches 2.
- Whenever satisfied == required, we record the candidate window and shrink left until a needed character falls below its required frequency.
Example 4 · Longest Repeating Character Replacement using maxFrequency in window
public class CharacterReplacementDemo { public static int characterReplacement(String s, int k) { int[] count = new int[26]; int left = 0; int maxFreq = 0; int best = 0;
for (int right = 0; right < s.length(); right++) { int idx = s.charAt(right) - 'A'; count[idx]++; maxFreq = Math.max(maxFreq, count[idx]);
while ((right - left + 1) - maxFreq > k) { count[s.charAt(left) - 'A']--; left++; } best = Math.max(best, right - left + 1); } return best; }
public static void main(String[] args) { System.out.println("ABAB (k=2): " + characterReplacement("ABAB", 2)); System.out.println("AABABBA (k=1): " + characterReplacement("AABABBA", 1)); }}ABAB (k=2): 4 AABABBA (k=1): 4
What this code does
- To make all characters in a window of length L identical, we keep the most frequent character (count maxFreq) and replace the remaining L - maxFreq characters.
- Whenever (right - left + 1) - maxFreq > k, we shrink left by one step.
This combines the shortest variable-size window template from Lesson 3 with the satisfied == required counter:
- Count frequencies of
tinint[] need = new int[128]and count how many distinct characters haveneed[c] > 0(required). - Expand
right: incrementwindow[c]. Ifneed[c] > 0 && window[c] == need[c], incrementsatisfied. while (satisfied == required): the current window[left .. right]coverst! Ifright - left + 1 < minLen, recordminLenandbestStart = left. Then shrink from the left: letout = s.charAt(left++); ifneed[out] > 0 && window[out] == need[out], decrementsatisfied; and decrementwindow[out].
Next step
Check your understanding
10 quick questions