Skip to contentKEEP THE CRAFTTHE SANCTUARY

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.

1 practice exercise3 interview problems

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.

Step Executed statement State Why
Seed total=sum(values[:width]); trace=[[0,width-1,total]] total=3, trace=[[0,1,3]] 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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Rolling sums of complete width-k windowsO(n)O(n)One initial O(k) sum is followed by n-k constant-time arithmetic updates.

Space

O(1) rolling entries, with O(min(width,n)) peak auxiliary space for the initial slice; the trace also returns O(n) entries.

Assumptions

  • Width is a positive integer. If it exceeds n, the trace returns [] and the maximum returns None.
  • Python values[:width] allocates the initial O(k) slice; keeping a numeric rolling total prevents an O(k) copy on every shift.

Invariants Worth Saying Aloud

  1. Before a trace entry is appended, total equals the sum from right-width+1 through right inclusive.
  2. The best sum is initialized from an actual complete window, so all-negative input cannot be replaced by an imaginary zero sum.

When To Use Or Avoid Fixed-size Window

Use It When

  • Calculate all fixed-width sums or the best sum in a single left-to-right pass.
  • Use negative values safely when width movement is predetermined and aggregation is additive.

Choose Another Tool When

  • Use a variable window when validity, rather than a prescribed width, determines the left edge.
  • Use prefix sums for many arbitrary static ranges; use a monotonic deque instead of simple subtraction for window maxima.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Subtracting the new left value

On the shift from [5, -2] to [-2, 4], right-width+1 names the retained -2, not the outgoing 5.

Prevent it: Subtract values[right-width]; use right-width+1 only to label the new left boundary.

Avoid

total += values[right]-values[right-width+1]

Use instead

total += values[right]-values[right-width]

Inventing a zero-sum candidate

When every complete sum is negative, zero is not an eligible window and must not seed the maximum.

Prevent it: Initialize best from the first complete sum rather than from a numeric convenience sentinel.

Avoid

best = max(0,total)

Use instead

best = total

Returning a partial seed when width is too large

The first slice silently shortens when width exceeds the list, so its sum can masquerade as a complete candidate.

Prevent it: Check whether a complete window exists before seeding; distinguish None from a legitimate zero sum.

Avoid

answer = sum(values[:width])

Use instead

answer = None if width > len(values) else sum(values[:width])

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.