On this page · Fix the Candidate Length Before Optimizing
Fixed-size Window
Compute one aggregate for exactly k contiguous items, then replace one leaving contribution with one entering contribution. A positive fixed width permits negative values and requires complete-window handling before maximizing.
Recognize it when Every candidate range has the same positive length.
Checking your account…
Fixed-size Window Code Labs
Fix the Candidate Length Before Optimizing
For a question about exactly k consecutive values, even a very large sum from a shorter tail is not an answer. Require positive k and decide how to report the absence of a complete range. With that contract settled, neighboring candidates differ by only one leaving and one entering value.
Seed Once and Preserve an Exact Total
The trace Lab starts with the first width values, then appends inclusive left/right indices and their total. At each shift, right-width is the old left index, while right-width+1 is the new left index. These similar expressions have different roles. Write their meanings before translating them into arithmetic.
Trace Fixed Window Updates
Reference
def fixed_window_trace(values,width):
if width>len(values): return []
total=sum(values[:width]); trace=[[0,width-1,total]]
for right in range(width,len(values)):
total+=values[right]-values[right-width]
trace.append([right-width+1,right,total])
return trace
Practice
Implement fixed_window_trace(values,width). Return [left,right,sum] for every complete window. width is a positive integer.
Public tests
Replace one leaving value
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Fixed Window Updates
def fixed_window_trace(values,width):
if width>len(values): return []
total=sum(values[:width]); trace=[[0,width-1,total]]
for right in range(width,len(values)):
total+=values[right]-values[right-width]
trace.append([right-width+1,right,total])
return trace
Replace One Contribution at Each Shift
The existing trace Lab on [5, -2, 4, 1] with width 2 shows why the leaving index is right-width. Negative values do not change the movement rule.
Exactly the first two values define the first complete candidate.
Shift to right=2
total+=values[right]-values[right-width]
total=3+4-5=2
5 leaves as 4 enters; the retained -2 stays counted.
Record new bounds
trace.append([right-width+1,right,total])
trace=[[0,1,3],[1,2,2]]
New left=1 differs from the leaving index 0.
Shift to right=3
total+=values[right]-values[right-width]
total=2+1-(-2)=5
Subtracting a negative leaving value increases the sum correctly.
Finish
return trace
[[0,1,3],[1,2,2],[2,3,5]]
No shorter trailing range is recorded.
Print
Output
print(fixed_window_trace([5, -2, 4, 1], 2))
[[0, 1, 3], [1, 2, 2], [2, 3, 5]]
Maximize Only Real Windows
The maximum Lab initializes best from the first complete sum. Starting best at zero would invent an empty candidate and give the wrong answer for all-negative values. Unlike a bounded variable sum window, fixed-width addition/subtraction does not rely on nonnegativity: its boundaries move by the contract, not by whether a sum improved.
Find Maximum Fixed Window Sum
Reference
def max_window_sum(values,width):
if width>len(values): return None
total=sum(values[:width]); best=total
for right in range(width,len(values)):
total+=values[right]-values[right-width]
best=max(best,total)
return best
Practice
Implement max_window_sum(values,width). Return the maximum sum of exactly width values, or None when no complete window exists. width is a positive integer.
Public tests
Compare every complete window
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Find Maximum Fixed Window Sum
def max_window_sum(values,width):
if width>len(values): return None
total=sum(values[:width]); best=total
for right in range(width,len(values)):
total+=values[right]-values[right-width]
best=max(best,total)
return best
Select the Aggregate’s Own Tool
Addition has an inverse, so subtracting the outgoing value updates a sum. A maximum has no corresponding subtraction operation: when its largest value leaves, another candidate must be found, usually with a monotonic deque. Prefix sums are useful for arbitrary static ranges but store O(n) prefix values, whereas one rolling pass needs constant working state.
Check Complete Ranges Before the Interview Claim
Before claiming linear time, account for the initial sum and its slice; the slice uses O(min(width,n)) peak auxiliary space even though the rolling entries are O(1); each subsequent update is constant work. Predict a single-element width, an all-negative maximum and a width larger than the list. Explain which value leaves and which enters on a concrete shift, then connect that same exact-width contract to the related radius-average exercise.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Fixed-size sliding window
Add the new, drop the old, record.
Every candidate is a contiguous block of exactly k items.
Trigger words
window of size k
k consecutive
subarray of length k
permutation in string
average of every k
def best_window_sum(nums, k):
window_sum = sum(nums[:k])
best = window_sum
for right in range(k, len(nums)):
window_sum += nums[right] # add the item coming in
window_sum -= nums[right - k] # drop the item going out
best = max(best, window_sum)
return best
Spot it when
'Subarray of length k' or 'every window of size k'.
Averages or sums over k consecutive items.
Remember
The window is nums[right - k + 1 : right + 1].
Updating the window in O(1) instead of re-summing it makes the scan O(n).
How problems bend it
Count characters in each window (anagram in a string): Keep a count dictionary instead of a sum and compare it with the target counts.
Distinct values in each window: Keep a count dictionary and delete a key when its count drops to zero.
Python Version Note
Python 3.11+
Python values[:width] allocates the initial O(k) slice; keeping a numeric rolling total prevents an O(k) copy on every shift.