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”- 1Minimum Size Subarray SumWalkthroughMediumBasic Anchor·LeetCode #209
- 2Subarray with Given Sum (non-negative numbers)WalkthroughEasyBasic Reinforcement·GeeksforGeeks
- 3Longest Substring Without Repeating CharactersWalkthroughMediumSlight Variation·LeetCode #3
- 4Max Consecutive Ones IIIWalkthroughMediumMedium·LeetCode #1004
- 5Longest Subarray of 1's After Deleting One ElementWalkthroughMediumPattern Transfer·LeetCode #1493
- 6Minimum Operations to Reduce X to ZeroWalkthroughMediumInterview-Level·LeetCode #1658
- 7Frequency of the Most Frequent ElementWalkthroughMediumTricky / Edge Case·LeetCode #1838
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?