← Visualizers
Sliding Window · sub-variant H — complement / inverse window LeetCode 1658

Minimum Operations to Reduce X to Zero / visualized

Each operation strips one element off the front or the back and subtracts it from x; you want the fewest operations that land x on exactly zero. The removed set straddles the two ends, so it is not a window — but the untouched middle is, and it must sum to exactly total − x. Deriving that number is the whole problem: after it, you are just finding the longest subarray with a given sum, and answer = n − longestMiddle (or −1 if no middle hits the number). Note the pairing with LC 1423: same complement move, but there the middle had a fixed width you slid, and here it is variable — grow on the right, shrink on the left whenever you overshoot. Both live in the syllabus so you meet the trick in both shapes.

Execution

idle
one picture, two readings  ·  orange ends = elements REMOVED  ·  teal middle = the window you KEEP
Press Run to begin.
0 / 0
Speed

Java · running line

removed (front + back) the kept middle entering the middle evicted — overshoot longest exact middle
O(n) time · O(1) space  ·  each index enters the middle once and leaves once. Sub-variant H: the removed set is split across both ends, so window its complement instead. target = total − x; the middle is variable-width here, unlike LC 1423's fixed one. Only sound because every value is positive — that is what makes the sum monotone in the boundaries.