Skip to contentKEEP THE CRAFTTHE SANCTUARY

Sliding Window

Reuse state for overlapping contiguous ranges instead of rebuilding every subarray. Choose a fixed-width update or a validity-controlled boundary, and prove when discarded left elements cannot help a later answer.

2 practice exercises2 interview problems

Recognize it when The answer is a contiguous segment and neighboring candidates overlap substantially.

Checking your account…

Sliding Window Code Labs

Keep the Overlap Instead of Rebuilding It

Start with list indexing and a contiguous subarray. Consecutive width-three sums share two elements, so summing each slice repeats work. A window stores a summary of the current range and changes it only for entering or leaving values. The summary might be a total, a frequency map or an extreme maintained by another structure; the window label alone does not determine that choice.

A Fixed Width Determines Both Boundaries

The first Lab assumes a positive width and seeds the first complete window once. Each next right index replaces exactly one contribution. Negative numbers do not break this arithmetic: no comparison decides whether a left value should be discarded. If width exceeds the input, there is no complete candidate.

Slide a Fixed Window

Reference
def fixed_window_sums(values, width):
    if width > len(values): return []
    total = sum(values[:width])
    result = [total]
    for right in range(width, len(values)):
        total += values[right] - values[right - width]
        result.append(total)
    return result
Practice

Implement fixed_window_sums(values, width). Return every contiguous sum of exactly width values; return [] when width exceeds the input. width is a positive integer.

Public tests

  • Update one entering and leaving value

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Slide a Fixed Window

def fixed_window_sums(values, width):
    if width > len(values): return []
    total = sum(values[:width])
    result = [total]
    for right in range(width, len(values)):
        total += values[right] - values[right - width]
        result.append(total)
    return result

Let a Monotone Constraint Move Left

The second Lab finds the longest window whose nonnegative sum stays under a limit. Expansion can only increase that sum; deleting a left value cannot increase it. After expansion, use a while loop to remove enough elements, then measure. A previously removed left value cannot help a later endpoint fit under the limit because further nonnegative expansion cannot repair the excess.

Find the Longest Bounded Window

Reference
def longest_window_at_most(values, limit):
    left = total = best = 0
    for right, value in enumerate(values):
        total += value
        while total > limit and left <= right:
            total -= values[left]
            left += 1
        best = max(best, right - left + 1)
    return best
Practice

Implement longest_window_at_most(values, limit). values contains nonnegative integers. Return the maximum contiguous window length whose sum is at most limit.

Public tests

  • Expand and restore validity

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find the Longest Bounded Window

def longest_window_at_most(values, limit):
    left = total = best = 0
    for right, value in enumerate(values):
        total += value
        while total > limit and left <= right:
            total -= values[left]
            left += 1
        best = max(best, right - left + 1)
    return best

Restore Validity More Than Once

Run the existing Lab on [3, 1, 4, 2] with limit 5. At the last expansion a single left removal is insufficient, so the while loop matters.

Step Executed statement State Why
Initialize left = total = best = 0 left=0, total=0, best=0 The empty prefix contributes no values.
First two values total += value; best = max(best, right - left + 1) right=1, total=4, best=2 Both expansions satisfy the limit, so lengths 1 then 2 are valid.
Enter 4 total += value right=2, total=8, left=0 Expansion temporarily violates the sum limit.
Remove 3 total -= values[left]; left += 1 total=5; left becomes 1 Removing the old left contribution restores validity.
Measure restored range best = max(best, right - left + 1) window=[1,4], length=2, best=2 The invalid length-three range was never a candidate.
Enter 2 total += value right=3, total=7 The new value creates another invalid window.
Remove 1 then 4 while total > limit and left <= right: total -= values[left]; left += 1 left=3, total=2 After removing 1 the sum was still 6; while removes a second element.
Return best return best best=2 The final length-one range does not replace the earlier best.
Print Output
print(longest_window_at_most([3, 1, 4, 2], 5)) 2

Choose the State and the Answer Timing

For a fixed width, measure every complete range. For a longest-valid variable range, measure after shrinking. For a shortest range that reaches a target, measure while the target is met and before each removal. These are different contracts, not interchangeable placements of max or min. Frequency-based windows must decrement leaving counts and delete zero entries when the number of distinct keys determines validity.

Choose Windows or Prefix State in an Interview

Negative values can make an over-limit window valid again after a later expansion, so the nonnegative shrinking proof fails. Prefix sums and appropriate lookup or monotonic structures are alternatives for those questions. Prefix sums also suit arbitrary static ranges, while a rolling window uses less working memory for one ordered pass. Longest Unique-Character Window(opens in a new tab) transfers the boundary invariant to character counts, not the sum-specific condition.

The at-most validity discussion assumes a nonnegative limit; a return value of 0 also represents the absence of any valid nonempty candidate.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Fixed sum or monotone variable-window scanO(n)O(n)The fixed Lab seeds one O(width) sum, then uses constant work per slide; the variable Lab advances each boundary at most n times.

Space

O(1) rolling state for the variable Lab; the fixed Lab uses O(width) peak auxiliary space for its seed slice plus O(n) possible output.

Assumptions

  • Fixed width is positive. Variable sum shrinking assumes nonnegative values; validity direction and answer-update placement depend on the objective.
  • Python slices allocate lists; the one initial seed slice costs O(width), whereas slicing and summing every candidate would cost O(n * width).

Invariants Worth Saying Aloud

  1. The running summary describes exactly the elements within the current boundaries.
  2. For the longest-bounded Lab, the recorded candidate satisfies total <= limit after all required left removals.

When To Use Or Avoid Sliding Window

Use It When

  • Compute all sums of one positive fixed width with one rolling total.
  • Find a longest nonnegative-sum window under a limit by restoring validity before measuring.
  • For the at-most validity invariant including an empty range, the limit is nonnegative.

Choose Another Tool When

  • Use prefix sums for many independently chosen immutable range queries.
  • Use prefix-state methods when negative values make sum-based left shrinking unsafe; fixed-width rolling sums still work with negative values.

Common Pitfalls

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

Measuring before the window is valid

After adding 4 to [3, 1], the length-three range sums to 8 and is invalid for limit 5. Updating best first records a forbidden answer.

Prevent it: Restore the bounded-sum invariant before comparing candidate length.

Avoid

best = max(best, right-left+1)

Use instead

while total > limit and left <= right:
    total -= values[left]
    left += 1
best = max(best, right-left+1)

Keeping zero-count keys in distinct state

A leaving character with count zero is no longer in the window, but len(counts) still includes its key and may force unnecessary shrinking.

Prevent it: Delete a key when its count reaches zero if distinct-key count is the validity measure.

Avoid

counts[leaving] -= 1

Use instead

counts[leaving] -= 1
if counts[leaving] == 0:
    del counts[leaving]

Including trailing partial fixed windows

Iterating every start emits sums for shorter tails, which do not contain the required positive width.

Prevent it: Generate only starts whose entire window fits, or slide the existing seeded aggregate.

Avoid

totals = [sum(values[start:start+width]) for start in range(len(values))]

Use instead

totals = [sum(values[start:start+width]) for start in range(len(values)-width+1)]

Reviewed References

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