Loading
Loading
A contiguous range that grows and shrinks instead of restarting.
Maintain a window over a contiguous run of elements together with a summary of what it contains — a sum, a count, a frequency map. Extend the right edge to take in new elements; pull the left edge in when the window violates its condition. Because each edge only ever moves forward, every element is added once and removed at most once, turning a quadratic re-scan into a linear sweep.
Ask two questions. When do I grow the window, and when must I shrink it? If both answers are one-directional, the two edges never move backwards and the sweep is linear.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def variable_window(items): """Grow on the right; shrink from the left while the window is invalid.""" left = 0 best = 0 state = {} # whatever summary the condition needs for right, value in enumerate(items): add(state, value) # 'while', not 'if': one new element can force several removals. while not is_valid(state): remove(state, items[left]) left += 1 best = max(best, right - left + 1) return best def fixed_window(items, k): """Window of constant width: add one, drop one.""" if len(items) < k: return None total = sum(items[:k]) best = total for right in range(k, len(items)): total += items[right] - items[right - k] best = max(best, total) return best| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Strongest Signal Window#8 | Easy | Primary | |
| Longest Distinct Stretch#27 | Medium | Primary | |
| Longest Uniform Run After Swaps#28 | Medium | Primary | |
| Shortest Covering Run#29 | Hard | Primary | |
| Count Low-Product Windows#30 | Medium | Primary | |
| Densest Signal Window#31 | Easy | Primary | |
| Rolling Peak#46 | Hard | Related | |
| Recent Request Counter#47 | Easy | Primary |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in