Python 3.11+
Python slices allocate lists; the one initial seed slice costs O(width), whereas slicing and summing every candidate would cost O(n * width).
Verify in Python docs(opens in a new tab)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…
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.
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.
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 resultImplement fixed_window_sums(values, width). Return every contiguous sum of exactly width values; return [] when width exceeds the input. width is a positive integer.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 resultThe 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.
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 bestImplement longest_window_at_most(values, limit). values contains nonnegative integers. Return the maximum contiguous window length whose sum is at most limit.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 bestRun 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. |
| Output | |
|---|---|
print(longest_window_at_most([3, 1, 4, 2], 5)) |
2 |
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.
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 3.11+
Python slices allocate lists; the one initial seed slice costs O(width), whereas slicing and summing every candidate would cost O(n * width).
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Fixed sum or monotone variable-window scan | O(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. |
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.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
best = max(best, right-left+1)while total > limit and left <= right:
total -= values[left]
left += 1
best = max(best, right-left+1)Where you will hit this: Slide a Fixed Window(opens in a new tab)
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.
counts[leaving] -= 1counts[leaving] -= 1
if counts[leaving] == 0:
del counts[leaving]Where you will hit this: Slide a Fixed Window(opens in a new tab)
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.
totals = [sum(values[start:start+width]) for start in range(len(values))]totals = [sum(values[start:start+width]) for start in range(len(values)-width+1)]Where you will hit this: Longest Substring Without Repeating Characters(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27