Overview (Fixed Length)
Master the fixed-size sliding window pattern: slide one element out, slide one element in.
What is a Fixed Length Window?
In a Fixed Length sliding window, the size of the window k never changes. Visualizing it is simple: imagine a rigid frame of size k sliding across your array one step at a time.
The Golden Rule:
At each step, we do exactly two things in O(1) time:
- Remove the element leaving the window (the one at
i - k). - Add the element entering the window (the one at
i).
This "Add-Remove" strategy avoids re-calculating the window content from scratch, turning an O(N*K) brute force algorithm into an O(N) linear solution.
Core Problem: Maximum Sum Subarray of Size K
The classic problem to learn this pattern:
Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.
Example:
- Input:
nums = [2, 1, 5, 1, 3, 2],k = 3 - Output:
9 - Explanation: Subarray
[5, 1, 3]has the largest sum.
Algorithm Strategy
- Initialize: Calculate the sum of the first
kelements. Set this as your initialcurrent_sumandmax_sum. - Slide: Iterate from index
kto the end of the array. - Update: For each new element at index
i:- Add
nums[i]tocurrent_sum. - Subtract
nums[i - k](the element falling out) fromcurrent_sum. - Update
max_sum = max(max_sum, current_sum).
- Add
- Return:
max_sum.
Visual Walkthrough
Initializing...
Watch how the window slides. Notice that we don't re-add the middle elements; we purely adjust for the entering and leaving numbers.
Dry Run: [2, 1, 5, 1, 3, 2], k=3
| Step | Window Indices | Window Values | Operation | Current Sum | Max Sum |
|---|---|---|---|---|---|
| Init | [0, 2] |
[2, 1, 5] |
Sum first 3 | 2+1+5 = 8 |
8 |
| Slide 1 | [1, 3] |
[1, 5, 1] |
Add 1, Remove 2 | 8 + 1 - 2 = 7 |
8 |
| Slide 2 | [2, 4] |
[5, 1, 3] |
Add 3, Remove 1 | 7 + 3 - 1 = 9 |
9 |
| Slide 3 | [3, 5] |
[1, 3, 2] |
Add 2, Remove 5 | 9 + 2 - 5 = 6 |
9 |
| End | Result: 9 |
Edge Cases & Common Mistakes
Edge Cases:
- Array length < k: Checking should happen immediately. Usually return 0 or error.
- k = 1: The problem reduces to finding the maximum element in the array.
Common Mistakes:
- Off-by-one errors: Calculating the index of the element leaving (
i - kvsi - k + 1etc). If iteratingifrom0to end, the leaving element isi - konly afteri >= k-1. - Re-summing: Using a loop inside the loop to sum the window elements, leading to O(N*K) complexity.
The Code Template
This template applies to almost any fixed-window problem (Generic inputs are used).
1def max_sum_subarray(nums, k):2 n = len(nums)3 if n < k: return 045 # 1. Initialize first window6 current_sum = sum(nums[:k])7 max_sum = current_sum89 # 2. Slide the window10 # window ends at i, so it starts at i - k + 111 # element leaving is at index i - k12 for i in range(k, n):13 current_sum += nums[i] # Add new14 current_sum -= nums[i - k] # Remove old15 max_sum = max(max_sum, current_sum)1617 return max_sum
Complexity Analysis
- Time Complexity: O(N). We iterate through the array once. Each step involves constant time math operations.
- Space Complexity: O(1). We strictly use a few variables (
current_sum,max_sum) regardless of input size.
- What is a Fixed Length Window?
- Core Problem: Maximum Sum Subarray of Size K
- Algorithm Strategy
- Visual Walkthrough
- Dry Run: [2, 1, 5, 1, 3, 2], k=3
- Edge Cases & Common Mistakes
- The Code Template
- Complexity Analysis
