On this page · Ask Whether Removing Left Can Only Help
Variable-size Window
Let a monotone validity rule move the left boundary while right advances once. Longest windows under a limit and shortest windows reaching a target require opposite answer-update timing and explicit numeric preconditions.
Recognize it when The segment must be contiguous but its length is chosen by a validity condition.
Checking your account…
Variable-size Window Code Labs
Ask Whether Removing Left Can Only Help
A variable-length question does not automatically admit a sliding window. For nonnegative sums, adding right cannot reduce the total and removing left cannot increase it. This monotonicity lets a start be discarded permanently. Negative values can reverse either effect, so verify the numeric domain before choosing a shrink rule.
Restore a Longest-Valid Window Completely
The boundary trace adds each value, removes left values while the sum exceeds limit, and records the restored inclusive boundaries. Several removals can be necessary. When one value alone exceeds limit, left may become right+1: this represents an empty range with total zero, not a one-element answer. The at-most trace requires a nonnegative limit so this empty range still satisfies the bound.
Trace Variable Window Boundaries
Reference
def bounded_window_trace(values, limit):
left = total = 0
trace = []
for right, value in enumerate(values):
total += value
while total > limit and left <= right:
total -= values[left]
left += 1
trace.append([left, right, total])
return trace
Practice
Implement bounded_window_trace(values, limit). values and limit are nonnegative. Return [left, right, sum] after shrinking each right-expanded window to sum at most limit; left=right+1 denotes an empty range.
Public tests
Restore validity after expansion
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Variable Window Boundaries
def bounded_window_trace(values, limit):
left = total = 0
trace = []
for right, value in enumerate(values):
total += value
while total > limit and left <= right:
total -= values[left]
left += 1
trace.append([left, right, total])
return trace
Trace an Oversized Value into an Empty Window
Use bounded_window_trace([2, 6, 1], 4). The oversized middle value requires two removals, including itself.
Step
Executed statement
State
Why
Initialize
left = total = 0
left=0, total=0, trace=[]
No range has entered yet.
Enter 2
total += value; trace.append([left, right, total])
right=0, total=2, trace=[[0,0,2]]
The first range already satisfies the limit.
Enter 6
total += value
right=1, total=8
The new total violates the limit.
Remove 2
total -= values[left]; left += 1
left=1, total=6
One removal leaves the oversized value, so shrinking must continue.
Remove 6
total -= values[left]; left += 1; trace.append([left, right, total])
left=2, right=1, total=0
left > right represents an empty valid range.
Enter 1
total += value
left=2, right=2, total=1
The next expansion starts a new nonempty range without moving left backward.
Return
return trace
[[0,0,2],[2,1,0],[2,2,1]]
Every observation is recorded after validity is restored.
Print
Output
print(bounded_window_trace([2, 6, 1], 4))
[[0, 0, 2], [2, 1, 0], [2, 2, 1]]
Measure Before Shrinking a Shortest-Sufficient Window
The second Lab assumes positive values and a positive target. Once total reaches target, the current range is eligible; record its length before removing left. Continue while sufficient to examine every shorter eligible range for that same right endpoint. Measuring only after sufficiency disappears would record an invalid answer or miss the last valid range.
Find Minimum Window Reaching a Target
Reference
def min_window_at_least(values, target):
left = total = 0
best = len(values) + 1
for right, value in enumerate(values):
total += value
while total >= target:
best = min(best, right - left + 1)
total -= values[left]
left += 1
return 0 if best > len(values) else best
Practice
Implement min_window_at_least(values, target). values contains positive integers. Return the minimum contiguous length with sum at least target, or 0. target is a positive integer.
Public tests
Shrink while the target remains met
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Find Minimum Window Reaching a Target
def min_window_at_least(values, target):
left = total = 0
best = len(values) + 1
for right, value in enumerate(values):
total += value
while total >= target:
best = min(best, right - left + 1)
total -= values[left]
left += 1
return 0 if best > len(values) else best
Treat the Two While Conditions as Different Proofs
Longest-at-most removes invalid starts until validity returns. Shortest-at-least removes valid starts after recording them to look for a shorter candidate. In both cases, each left step is permanent because the numeric precondition controls how the sum can change. A zero or negative target is outside the minimum Lab’s contract; it needs a separately defined empty-window behavior, not an unchecked reuse of this loop.
Transfer Window State Carefully in an Interview
Character or distinct-value constraints use frequency state rather than numeric sums, and their validity proof must be stated independently. Prefix state is the nearest alternative when sums can decrease on expansion. Practice an oversized single element in the bounded Lab and an unreachable target in the minimum Lab; then explain why total still matches the current indices after every removal.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Variable-size sliding window
Watch: Variable-size sliding window in 4 minutes, with Quill.
Expand right; while the window is invalid, shrink left; then record.
You want the longest (or shortest) contiguous block that satisfies a rule, and shrinking a window never makes it 'more invalid'.
Trigger words
longest substring
longest subarray
shortest subarray
minimum window
at most k
without repeating
def longest_valid_window(s, k):
count = {}
left = 0
best = 0
for right, char in enumerate(s):
count[char] = count.get(char, 0) + 1 # 1. expand: take s[right]
while len(count) > k: # 2. invalid? shrink from the left
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
best = max(best, right - left + 1) # 3. the window is valid: record it
return best
Spot it when
'Longest substring/subarray such that ...'.
'Shortest subarray with sum at least ...'.
'At most k' of something.
Remember
The knob is the 'invalid' test in the while loop; everything else stays the same.
Each item enters once and leaves once, so the two loops together are O(n).
For the shortest window, record inside the while loop (while valid: record, then shrink).
How problems bend it
Shortest window that is valid: Expand right; while valid, record, then shrink: update best first, then remove s[left] and move left.
Count windows with at most k: Add right - left + 1 after the while loop; exactly k = at most k minus at most k - 1.
No repeated characters: Invalid means count[char] > 1 for the character just added.
Replace at most k characters: Invalid means window length - most frequent count > k.
Python Version Note
Python 3.11+
Python integer arithmetic is exact, but the usual O(n) bound assumes bounded-size arithmetic; moving indices avoids repeated O(window length) slices.
Interview bounds depend on the stated representation, input model, and real Python operations.
Operation
Average
Worst
Interview note
Monotone sum-window scan
O(n)
O(n)
Each item enters once and leaves at most once; nested while iterations therefore total O(n).
Space
O(1) working state; the boundary-trace Lab stores O(n) observations.
Assumptions
The bounded trace requires nonnegative values; the minimum Lab requires positive values and a positive target. Negative values invalidate this sum-based rejection proof.
Python integer arithmetic is exact, but the usual O(n) bound assumes bounded-size arithmetic; moving indices avoids repeated O(window length) slices.
The at-most trace uses nonnegative values and a nonnegative limit, including its zero-sum empty-range states.
Invariants Worth Saying Aloud
In the bounded trace, total describes the inclusive [left,right] range and is at most limit after the shrink loop.
In the minimum Lab, every range measured inside while reaches target; shrinking then explores shorter candidates for the same right endpoint.
When To Use Or Avoid Variable-size Window
Use It When
For nonnegative values, maintain a longest sum-at-most window by shrinking until valid.
For positive values and a positive target, find a shortest sum-at-least window by measuring before each valid shrink.
For the at-most validity invariant including an empty range, the limit is nonnegative.
Choose Another Tool When
Do not use sum-based monotone shrinking with negative values; prefix sums and appropriate lookup or deque techniques may be needed.
Use a fixed window when a required length determines movement without testing validity.
Common Pitfalls
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
01
Shrinking only once
After [2, 6] exceeds limit 4, removing 2 leaves sum 6; an if branch records a range that remains invalid.
Prevent it: Use while until the invariant is restored, including the empty-range case.
Avoid
if total > limit and left <= right:
total -= values[left]
left += 1
Use instead
while total > limit and left <= right:
total -= values[left]
left += 1
Discarding starts when later negatives can repair them
The prefix [5] exceeds limit 3, but adding -4 would make the length-two range valid. A monotone shrink based on nonnegative assumptions has already discarded that start.
Prevent it: Validate the nonnegative precondition or select a prefix-based method before applying this sum rule.