2Brute2Best
🔥0
03

Variable Window + Frequency Map (Sliding Window Sub-pattern)

A variable window whose rule depends on counts inside it — how many distinct values, how often the most common letter appears, whether required letters are all present.

Signals in the problem statement
  • ›

    "at most k distinct"

  • ›

    "replace at most k characters"

  • ›

    "contains all characters of t"

  • ›

    "each character appears at least / at most…"

What makes it different

The state is a count map (array of 26/128 or hash map), plus maybe one extra number such as distinct or maxFreq. Updating it correctly on remove is where bugs live.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Fruit Into Baskets
    Basic Anchor·LeetCode #904
    Medium
  2. 2
    Longest Substring with K Unique Characters
    Basic Reinforcement·GeeksforGeeks
    Medium
  3. 3
    Longest Repeating Character Replacement
    Slight Variation·LeetCode #424
    Medium
  4. 4
    Maximize the Confusion of an Exam
    Medium·LeetCode #2024
    Medium
  5. 5Medium
  6. 6
    Minimum Window Substring
    Interview-Level·LeetCode #76
    Hard
  7. 7Medium

Template

variable-template.cpp
// Variable window: grow on the right, shrink on the left while invalid.
int longestValidWindow(vector<int>& a) {
    int left = 0, best = 0;
    // state describing the current window (sum, counts, ...)
    for (int right = 0; right < (int)a.size(); right++) {
        add(a[right]);                    // 1. expand: include a[right]
        while (!valid()) {                // 2. shrink until valid again
            remove(a[left]);
            left++;
        }
        best = max(best, right - left + 1); // 3. window [left..right] is valid
    }
    return best;
}
Remember this · Sliding Window
Trigger
Contiguous subarray / substring + longest, shortest, maximum, count, or "of size K".
Think
Can I keep a valid range and move it, instead of checking every subarray from scratch?
Key question
When is my current window valid?