When can two moving boundaries replace a search?
Picture
A window is a contiguous stretch with a left and right boundary. If extending it changes a quantity predictably, you can move boundaries forward instead of retrying every stretch. The useful pattern is the rule that makes discarded boundaries permanently unnecessary.
Predict
To find the longest subarray with sum at most 5, you discard leftmost elements whenever the sum exceeds 5. What happens on [6, -2]?
Reveal the reasoning
You discard 6 immediately and miss the valid length-two sum 4. A later negative number can rescue a window that previously looked too large. The familiar sum-window rule needs nonnegative values.
Go deeper: the property behind the template
With nonnegative values and a nonnegative limit, extending right cannot reduce the sum; moving left forward cannot increase it. If a prefix already makes the sum too large, keeping that same left boundary through later extensions cannot help.
def longest_within_limit(values, limit):
left = total = best = 0
for right, value in enumerate(values):
total += value
while total > limit:
total -= values[left]
left += 1
best = max(best, right - left + 1)
return best
assert longest_within_limit([2, 1, 3, 1], 4) == 2
assert longest_within_limit([0, 0], 0) == 2
assert longest_within_limit([], 5) == 0
The inner loop may run many times in one iteration, but the left boundary never moves backward. Each element enters and leaves at most once: O(n) time and O(1) extra space.
Now change the objective to counting subarrays with exact sum k, allowing negative values. Prefix sums and a frequency dictionary can work: if the current prefix is s, every earlier prefix equal to s-k identifies one answer. That uses an algebraic equality, not window monotonicity. It is a different objective from “longest sum at most k”; do not substitute it unchanged.
Analogy limit: a contiguous window cannot represent arbitrary subsequences that skip elements. Also, other window problems have other invariants; negative values do not invalidate every sliding-window algorithm.
Change one rule
The input is a string and the window may contain no repeated character. What makes a forward-moving left boundary safe?
Check the variation
Once a duplicate exists, adding characters cannot remove it. Remove from the left until the duplicate is gone; those earlier starts could not produce a valid window ending here or later while retaining both copies.
Connect
Subsequence DP permits skipped positions. Counterexamples train you to inspect the property behind an attractive local rule.