← Visualizers
Sliding Window · anti-pattern LeetCode 560

Subarray Sum Equals K / visualized

A sliding window needs a direction: extending right must push the sum one way, shrinking left must push it the other, so that “too big” and “too small” each have exactly one legal move. With negative values in the array, adding an element can lower the sum, and the window is left with no rule for when to shrink — it has no legal move at all. Act 1 runs the window anyway and undercounts. Act 2 drops the window for prefix sums and a hash map of counts: count += seen[P − k], then seen[P]++. Two details do all the work — the map is seeded with seen[0] = 1 for the empty prefix, and the lookup happens before the insert.

Execution

idle
a  the array
P  running prefix · sum(a[x…y]) = P[y+1] − P[x]
seen  prefix value → how many times
Press Run to begin.
0 / 0
Speed

Java · running line

act 1
left / window start right / current index the key being looked up subarray counted missed by the window
Act 1 O(n) and wrong · Act 2 O(n) time, O(n) space  ·  when the predicate is not monotone in the window, stop looking for a shrink rule — reach for prefix[j] = prefix[i] − k and let a hash map hold every start index at once.