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.

3 variations · 8 problems · 4 with animated walkthroughs

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

Sliding Window · Hash Map
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);
}

The variations

  1. 1Cover every required value

    Count what is still missing. When nothing is missing, record the window and shrink until something is missing again.

  2. 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).

  3. 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.

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 size wrongly, or the reverse: forgetting to remove it when size is what you count.
  • For "exactly k distinct", trying to slide directly: use atMost(k) − atMost(k − 1).
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.