Arrays & Hashing · Pattern 13 of 26
Sliding window with a hash map
When the rule is about which values are inside the window (cover every letter of t, at most k distinct values), keep their counts in a hash map plus one number that says how many requirements are met.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The smallest window that contains all characters of another string
- At most (or exactly) k distinct values
- Nearby values within a distance, not just nearby indexes
The template
String minWindow(String s, String t) {
Map<Character, Integer> need = new HashMap<>();
for (char c : t.toCharArray()) need.merge(c, 1, Integer::sum);
int missing = t.length(), bestL = 0, bestLen = Integer.MAX_VALUE;
for (int l = 0, r = 0; r < s.length(); r++) {
char c = s.charAt(r);
if (need.getOrDefault(c, 0) > 0) missing--; // this char was still needed
need.merge(c, -1, Integer::sum);
while (missing == 0) { // valid: shrink as far as possible
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
char d = s.charAt(l++);
need.merge(d, 1, Integer::sum);
if (need.get(d) > 0) missing++; // removed a needed char
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestL, bestL + bestLen);
} def min_window(s, t):
need = {}
for c in t:
need[c] = need.get(c, 0) + 1
missing, best_l, best_len, l = len(t), 0, float('inf'), 0
for r, c in enumerate(s):
if need.get(c, 0) > 0:
missing -= 1 # this char was still needed
need[c] = need.get(c, 0) - 1
while missing == 0: # valid: shrink as far as possible
if r - l + 1 < best_len:
best_l, best_len = l, r - l + 1
need[s[l]] += 1
if need[s[l]] > 0:
missing += 1 # removed a needed char
l += 1
return "" if best_len == float('inf') else s[best_l:best_l + best_len] string minWindow(string s, string t) {
unordered_map<char, int> need;
for (char c : t) need[c]++;
int missing = t.size(), bestL = 0, bestLen = INT_MAX;
for (int l = 0, r = 0; r < (int)s.size(); r++) {
if (need[s[r]]-- > 0) missing--; // this char was still needed
while (missing == 0) { // valid: shrink as far as possible
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
if (++need[s[l++]] > 0) missing++; // removed a needed char
}
}
return bestLen == INT_MAX ? "" : s.substr(bestL, bestLen);
} function minWindow(s, t) {
const need = new Map();
for (const c of t) need.set(c, (need.get(c) ?? 0) + 1);
let missing = t.length, bestL = 0, bestLen = Infinity;
for (let l = 0, r = 0; r < s.length; r++) {
const c = s[r];
if ((need.get(c) ?? 0) > 0) missing--; // this char was still needed
need.set(c, (need.get(c) ?? 0) - 1);
while (missing === 0) { // valid: shrink as far as possible
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
const d = s[l++];
need.set(d, need.get(d) + 1);
if (need.get(d) > 0) missing++; // removed a needed char
}
}
return bestLen === Infinity ? "" : s.slice(bestL, bestL + bestLen);
} The variations
-
1Cover every required value
Count what is still missing. When nothing is missing, record the window and shrink until something is missing again.
Now you solve -
2At most k distinct
Keep counts in a map; shrink while the map has more than k keys. "Exactly k" = atMost(k) − atMost(k − 1).
Now you solve -
3Window plus an ordered structure
When the rule is about values being close (within t), keep the window in buckets of size t + 1 or a sorted set. Requests in a time window work the same way after sorting by time.
Now you solve
Mistakes to avoid
- Comparing whole count maps on every step: track one "missing" (or "formed") counter instead.
- Removing a key from the map when its count hits zero, then reading
sizewrongly, or the reverse: forgetting to remove it whensizeis what you count. - For "exactly k distinct", trying to slide directly: use atMost(k) − atMost(k − 1).
Lesson done
Next: Hashing: count, group and map →Mark it done once you can write the template from memory and you have solved the worked examples yourself.