← Visualizers
Sliding Window · anti-pattern LeetCode 862

Shortest Subarray with Sum at Least K / visualized

LeetCode 209 promises a[i] > 0. LeetCode 862 does not, and that single missing guarantee is the entire problem. With only positives, growing the window can only raise the sum and shrinking can only lower it — so shrink while still valid is safe, because the first left that breaks validity is the last one worth trying. Put one negative in the array and shrinking from the left can raise the sum, so that rule stops early and throws away a candidate it should have kept. Act 1 runs the 209 window and lets it return the wrong length. Act 2 throws the window away: prefix sums plus a monotonic deque of indices kept increasing in prefix value.

Execution

idle
a  the array
P  prefix sums · P[i] = sum of the first i values
deque · front → back, prefix values increasing
Press Run to begin.
0 / 0
Speed

Java · running line

act 1
left / window start right / current index deque front — best start recorded answer evicted · never examined
Act 1 O(n) but wrong · Act 2 O(n) time, O(n) space — every index is pushed once and popped once  ·  a window is legal only when the predicate is monotone in the window; with a negative in the array sum >= k is not, so the deque replaces the left pointer with all the left candidates still worth keeping.