← Visualizers
Sliding Window · variable window, sub-variant B — maximise LeetCode 1493

Longest Subarray of 1’s After Deleting One Element / visualized

Deleting one element from a run of 1s is the same as being allowed to carry one zero inside the window. So the invariant is simply zeros ≤ 1: r always advances, and while the window is invalid (two zeros) l walks right until it has thrown the older zero out. best is recorded after the shrink loop, where the window is legal again — that placement is the whole of sub-variant B. Two traps live here. Tracking the index of the single zero makes the eviction obvious instead of magical, and the answer is best − 1, not best, because the deletion is mandatory: an array of all 1s must return n − 1.

Execution

idle
nums  ·  dotted cells are zeros  ·  teal is inside the window
Press Run to begin.
0 / 0
Speed

Java · running line

inside the window entering evicted longest window recorded left behind
O(n) time · O(1) space  ·  l only ever moves right, so the inner loop is amortised O(1). Sub-variant B: record best after the shrink loop. Then subtract one — you must delete an element even when there was nothing wrong with the window.