1.1 Fixed-Size Sliding Window
Very CommonSummary: Maintain a window of exactly k elements, sliding it one step at a time while updating an aggregate (sum, max, count) in O(1) per step instead of recomputing from scratch.
Identification Signals - "Subarray/substring of size exactly K" - "Maximum/average/sum of every window of size k" - Fixed contiguous range, no shrinking/growing logic needed
Core Strategy
1. Compute the aggregate for the first k elements.
2. Slide right by one: add incoming element, remove outgoing (leftmost) element.
3. Update the running best answer at each slide.
C# Pseudo-code Template
// PSEUDO-CODE: Fixed Window Aggregate
public int MaxSumFixedWindow(int[] nums, int k)
{
int windowSum = 0;
for (int i = 0; i < k; i++) windowSum += nums[i]; // seed first window
int maxSum = windowSum;
for (int right = k; right < nums.Length; right++)
{
windowSum += nums[right] - nums[right - k]; // add new, drop old
maxSum = Math.Max(maxSum, windowSum);
}
return maxSum;
}
Benchmarks (Medium/Hard-weighted) - Warmup (optional): 643. Maximum Average Subarray I - Medium: 2461. Maximum Sum of Distinct Subarrays With Length K, 1052. Grumpy Bookstore Owner - Hard: 239. Sliding Window Maximum (combines with Monotonic Deque)
Pitfalls
- Off-by-one when removing the outgoing element: it's nums[right - k], not nums[right - k - 1].
- Forgetting to initialize the first window before the loop starts.