01
Fixed Window (Sliding Window Sub-pattern)
The window size is given and never changes. You never decide when to shrink — every step you add one element on the right and remove one on the left.
Signals in the problem statement
- ›
"subarray of size k"
- ›
"k consecutive elements"
- ›
"every window of length k"
- ›
"anagram / permutation of p" (window size = length of p)
What makes it different
No validity check and no while loop. The only job is to keep the aggregate (sum, counts) correct as the window slides.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Maximum Sum Subarray of Size KWalkthroughEasyBasic Anchor·GeeksforGeeks
- 2Maximum Average Subarray IWalkthroughEasyBasic Reinforcement·LeetCode #643
- 3Number of Sub-arrays of Size K and Average ≥ ThresholdWalkthroughMediumSlight Variation·LeetCode #1343
- 4Permutation in StringWalkthroughMediumMedium·LeetCode #567
- 5Find All Anagrams in a StringWalkthroughMediumPattern Transfer·LeetCode #438
- 6Maximum Points You Can Obtain from CardsWalkthroughMediumInterview-Level·LeetCode #1423
- 7Maximum Sum of Distinct Subarrays With Length KWalkthroughMediumTricky / Edge Case·LeetCode #2461
Template
fixed-template.cpp
// Fixed window of size k: add the element entering, remove the element leaving.
long long fixedWindow(vector<int>& a, int k) {
long long window = 0, best = LLONG_MIN;
for (int right = 0; right < (int)a.size(); right++) {
window += a[right]; // 1. element enters on the right
if (right >= k) window -= a[right - k]; // 2. element leaves on the left
if (right >= k - 1) best = max(best, window); // 3. window is full: use it
}
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?