2Brute2Best
🔥0
02

Variable Window (Sliding Window Sub-pattern)

The window grows and shrinks. You grow it on the right every step, and shrink it from the left only when it breaks a rule.

Signals in the problem statement
  • ›

    "longest / shortest subarray such that…"

  • ›

    "sum ≥ target" with positive numbers

  • ›

    "without repeating characters"

  • ›

    "at most k zeros can be flipped"

What makes it different

You must define validity. The window size is the answer (or part of it), not an input.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Minimum Size Subarray Sum
    Basic Anchor·LeetCode #209
    Medium
  2. 2
    Subarray with Given Sum (non-negative numbers)
    Basic Reinforcement·GeeksforGeeks
    Easy
  3. 3Medium
  4. 4
    Max Consecutive Ones III
    Medium·LeetCode #1004
    Medium
  5. 5Medium
  6. 6
    Minimum Operations to Reduce X to Zero
    Interview-Level·LeetCode #1658
    Medium
  7. 7
    Frequency of the Most Frequent Element
    Tricky / Edge Case·LeetCode #1838
    Medium

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?