← Visualizers
Sliding Window · at‑most‑K → exactly‑K LeetCode 930

Binary Subarrays With Sum / visualized

You cannot slide a window for exactly goal. The predicate is not monotone: extending the window to the right can carry you from sum == goal to sum > goal, and there is no shrink rule that lands you back — shrinking from the left can overshoot straight past the target. But sum ≤ s is monotone: once a window is too heavy, dropping elements only ever helps, so atMost(s) is windowable. That gives the whole sub-variant its identity: exactly(goal) = atMost(goal) − atMost(goal−1). Run the same O(n) window twice and subtract. Inside each pass, a valid window [l..r] banks r − l + 1 subarrays at once — one per suffix ending at r. Watch the edge: when goal = 0 the second pass is atMost(−1), which must be defined as 0, not run.

Execution

idle
the two passes, contribution by contribution
nums
≤ g
Σ 0
≤ g−1
Σ 0
exactly
Σ —
 
Press Run to begin.
0 / 0
Speed

Java · running line

inside the window entering on the right evicted on the left suffixes just banked pass 1 · atMost(goal) pass 2 · atMost(goal−1) fallen out
O(n) time · O(1) space  ·  two linear passes, still O(n). exactly(g) = atMost(g) − atMost(g−1) — the only reason it works is that sum ≤ s is monotone and sum == g is not.