PrepStack · Markdown HTML

Variable-size sliding window

Pointers and sliding window · HTML

Formal shape

Add each right endpoint once. While invalid for a longest-valid task, or while valid for a shortest-cover task, move left and remove its contribution. Both pointers are monotone.

Recognition signals

False friends

SignalWhy it is different
Sum constraint with arbitrary negativesExpanding can lower the sum and shrinking can raise it, destroying pointer monotonicity; use prefix state or a monotonic deque.
Noncontiguous subsequenceA window cannot skip intervening items.

Core invariant

left and right never retreat; whenever a result is recorded, the maintained state exactly matches [left,right] and satisfies the variant's validity or minimality condition.

State, transition, and processing order

ItemDefinition
Stateleft, right, window frequency/sum/missing count, and best; define symmetric add and remove operations.
TransitionAdd right, repeatedly remove left according to the objective until validity is restored or further contraction would break coverage, and update at the proper moment.
Frontier / orderAmong all windows ending at current right, monotonicity compresses candidates to one critical left boundary.

Python skeleton

def longest_at_most_k_distinct(values, k):
    if k < 0:
        return 0
    count, left, best = {}, 0, 0
    for right, value in enumerate(values):
        count[value] = count.get(value, 0) + 1
        while len(count) > k:
            old = values[left]
            count[old] -= 1
            if count[old] == 0:
                del count[old]
            left += 1
        best = max(best, right - left + 1)
    return best

Correctness sketch

  1. Symmetric add/remove keeps the frequency state equal to the actual interval.
  2. When distinct>k, every window with a smaller left is also invalid, so contraction discards no valid optimum.
  3. After validity returns, left is the farthest-left valid boundary for this right, so its length represents the best candidate ending here.

Complexity

TimeSpaceParameters
O(n)O(Σ)Each item enters once through right and leaves at most once through left; Σ is the number of distinct active keys.

Edge cases

Error patterns

PatternWhy it fails / fix
Using if instead of whileOne left move may not restore validity; contraction must continue.
Forcing every interval problem into a windowProve pointer monotonicity first, especially with negative values or nonmonotone predicates.
Updating at the wrong timeLongest-valid records after restoration; shortest-cover usually records while still covered and shrinking.

Selection and exclusion rules

RelationTemplateBoundary
also has left and rightOpposite-direction two pointersA window's state describes a contiguous aggregate rather than an endpoint pair.
same direction, different semanticsSame-direction / read-write pointersleft maintains a valid contiguous window rather than an output prefix.

Original micro-example

PartDetail
ResultThe longest valid window has length 3.
SetupSequence [a,b,a,c,c], allowing at most 2 distinct values.
TraceOn c, window a,b,a,c has 3 kinds, so left advances until b disappears; later c,c can extend.

Recall prompts

My notes