Intermediate · Module 7 · Lesson 1
Fixed-size window
Add the incoming value and remove the outgoing value.
Lesson 37 of 123
1d streakInteractive Visualization
Trace the algorithm state by state
Change the inputs, run an operation, and connect each visible state change to the explanation below.
Step-through visualizer
Fixed Sliding Window
Follow the state transition, then use the controls to test your prediction.
Fixed-Size Sliding Window: Reusing Intermediate Computations
When computing metrics over every contiguous subarray of fixed length k, a naive loop recalculates the window from scratch in O(k) per window, yielding O(n * k) overall. A sliding window maintains the state by adding the incoming element at the right edge and subtracting the outgoing element from the left edge in O(1) time.
Architectural Boundary · Do Not Confuse
Naive Recomputation: O(n * k)
Sliding Window: O(n)
A sliding window processes each element exactly twice: once when entering the right boundary and once when exiting the left boundary.
public int maxSumSubarray(int[] nums, int k) {
int currentSum = 0;
for (int i = 0; i < k; i++) currentSum += nums[i];
int maxSum = currentSum;
for (int i = k; i < nums.length; i++) {
currentSum += nums[i] - nums[i - k]; // Add incoming, remove outgoing
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}Active Recall Checkpoint
What happens if k > nums.length in a fixed-size sliding window problem?
Show answer & explanation
The input cannot form a valid window of size k; the algorithm must immediately handle this boundary edge case (returning 0 or throwing an IllegalArgumentException).
Use it when
Use fixed sliding windows for moving averages, maximum sum of size k, fixed-length anagram matching, and substring hash recalculations.
Reconsider when
Reconsider when window boundaries are dynamic and expand/contract based on condition predicates (use variable-size window).
Cost Model
Complexity & Trade-offs
Hands-On Practice
Implement: Max Subarray Sum (Fixed Window)
Write and test your solution in the browser against automated verification test cases.
Max Subarray Sum (Fixed Window)
Given an array of integers and an integer k, find the maximum sum of any contiguous subarray of size k.
When to use it
- Contiguous subarrays or substrings with incrementally maintainable state.
- Longest, shortest, count, sum, or frequency constraints.
- Streaming range calculations.
Common mistakes
- Using a variable window when feasibility is not monotonic under shrinking.
- Adding an incoming item but forgetting to remove the outgoing one.
- Updating the answer before the window is valid.
Practice prompts
- Reproduce the worked Fixed-size window example without looking at the trace.
- Change one input condition and explain whether the Fixed-size window invariant still holds.
- Implement the approach, derive its cost, and compare it with a straightforward baseline.
Mastery check