Stage 1 · Code
Two Pointers & Sliding Window
Fixed-Size Sliding Window
Maintain a window of exactly k elements — add the new element, remove the old, compute in O(1) per step.
7 min readLeetCode Patterns for InterviewsCode
The Pattern
For a fixed window of size k: compute the first window fully, then slide by adding nums[i] and removing nums[i-k] in O(1). Total: O(n) instead of O(n*k).
Fixed window max sum of k elements
def max_sum_window(nums: list[int], k: int) -> int:
"""Compute the maximum sum of any contiguous subarray of size k."""
# Compute first window
window_sum = sum(nums[:k])
max_sum = window_sum
# Slide the window
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k] # add new, remove old
max_sum = max(max_sum, window_sum)
return max_sum
# Usage
print(max_sum_window([2, 1, 5, 1, 3, 2], 3)) # 9 (5+1+3)
print(max_sum_window([2, 3, 4, 1, 5], 2)) # 7 (3+4)Key: the window has exactly k elements. When we advance by 1, we add the rightmost element and remove the leftmost (now k positions behind).
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.