sliding-window prefix-sum hash-lookup ⏱️ 8 min read • Updated 2026-10-19

Sliding Window vs Prefix Sum + Hash

The Non-Negative Monotonicity Rule and the Negative Numbers Trap

Why negative numbers break sliding windows completely, and how prefix sum hash maps recover O(N) lookup for arbitrary integer arrays.

⚡ The Discriminating Question

"Can the array numbers be negative, or does expanding the window move your condition in only one predictable direction?"

Ask this single question during the first two minutes of reading the problem prompt. The answer decides your fundamental pattern.

💡In Plain Words: Metro Smart Card Balance Ledger vs The Station Turnstile Counter

Think of a metro smart card transaction ledger. Every time you tap in or out, your balance is recorded. If your balance was Rs 120 at Rajiv Chowk and Rs 70 at Noida City Centre, the fare between those two stations is exactly Rs 120 minus Rs 70 = Rs 50. You do not need to walk between the stations or recount each rupee; the difference between two cumulative snapshots gives you the exact interval amount. Now think of a station turnstile counter that tracks the number of commuters entering in the last 15 minutes. It slides along the clock: new arrivals increment the count, and people who entered more than 15 minutes ago drop out. This works because people cannot un-enter the station (counts are strictly non-negative).

Key Takeaway: Use a Sliding Window when array values are non-negative and expanding the right boundary moves the sum strictly up. Use Prefix Sum with a Hash Map when negative numbers exist, because cumulative snapshots allow you to find target subarray sums regardless of whether numbers went up or down.

When to Choose Which Pattern

Sliding Window

Option A
Choose this when:
  • ✓All array elements are strictly non-negative (>= 0).
  • ✓The target condition is monotonic: expanding right strictly increases sum; advancing left strictly decreases sum.
  • ✓You want O(1) auxiliary space without allocating hash map buckets.
  • ✓The problem asks for minimum length, maximum length, or count under monotonic bounds.
Time ComplexityO(N) linear time with single-pass pointer moves
Auxiliary SpaceO(1) auxiliary memory

Prefix Sum + Hash Map

Option B
Choose this when:
  • ✓The array contains negative numbers, zeros, or arbitrary balance changes.
  • ✓You need to find a subarray with an exact sum K, or count all subarrays summing to K.
  • ✓The algebraic relation prefix[j] - prefix[i] = K translates into checking whether (current_prefix - K) exists in our hash map.
  • ✓Array elements cannot be reordered or sorted.
Time ComplexityO(N) single pass over the array
Auxiliary SpaceO(N) for storing seen prefix sums in a hash map

Side-by-Side Worked Examples

Compare concrete implementations side by side to see how the code structure diverges.

Minimum Size Subarray Sum(LC 209)

LeetCode ↗

The array contains strictly positive integers. Expand right and add nums[right] to current_sum. While current_sum >= target, record the window size (right - left + 1) and shrink the window from the left by subtracting nums[left]. Because numbers are positive, shrinking is guaranteed to decrease current_sum.

Python 3LC 209
def minSubArrayLen(target: int, nums: list[int]) -> int:
    left = 0
    current_sum = 0
    min_len = float('inf')
    for right, val in enumerate(nums):
        current_sum += val
        while current_sum >= target:
            min_len = min(min_len, right - left + 1)
            current_sum -= nums[left]
            left += 1
    return min_len if min_len != float('inf') else 0

Subarray Sum Equals K(LC 560)

LeetCode ↗

Maintain running sum prefix. A subarray ending at current index sums to k if prefix - k was seen earlier. Add map[prefix - k] to total answer, then increment map[prefix]. Seed the map with {0: 1} before starting to account for valid subarrays starting at index 0.

Python 3LC 560
def subarraySum(nums: list[int], k: int) -> int:
    prefix_counts = {0: 1}
    current_sum = 0
    total_count = 0
    for num in nums:
        current_sum += num
        diff = current_sum - k
        if diff in prefix_counts:
            total_count += prefix_counts[diff]
        prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
    return total_count

The Decision Matrix

Negative Numbers

Sliding Window

Breaks completely (monotonicity lost)

Prefix Sum + Hash Map

Handles negatives and zeros seamlessly

Extra Memory

Sliding Window

O(1) auxiliary space

Prefix Sum + Hash Map

O(N) hash map storage

Subarray Query Type

Sliding Window

Inequalities (>= K, <= K, at most K distinct elements)

Prefix Sum + Hash Map

Exact equality (sum == K, sum % K == 0)

State History

Sliding Window

Only requires tracking current left and right boundaries

Prefix Sum + Hash Map

Requires frequency or index history of previous cumulative sums

⚠️

Where Candidates Go Wrong (Top Traps)

✕

The LeetCode 560 sliding window trap

Why it fails in interviews: Candidates attempt two pointers on Subarray Sum Equals K. When nums has negative values (such as [1, -1, 1, -1, 1]), adding an element can reduce the sum. The pointer movement decisions become arbitrary guesses and fail.
✓The Senior Engineer Fix: Check problem constraints first: if nums[i] can be negative, immediately choose Prefix Sum + Hash Map.
✕

Forgetting the base seed {0: 1} in the prefix frequency map

Why it fails in interviews: If a subarray starting at index 0 sums exactly to K, then current_sum - K = 0. Without {0: 1} in the map, this valid subarray will be missed entirely.
✓The Senior Engineer Fix: Always initialize the prefix map with {0: 1} before entering the loop.
✕

Overwriting indices when searching for longest subarray

Why it fails in interviews: For the longest subarray with sum K, you need the earliest occurrence of a prefix sum. If you update the map on duplicate prefix sums, you shorten the potential window.
✓The Senior Engineer Fix: Only put prefix into the map if it does not already exist: if prefix not in map: map[prefix] = index.

Related Walkthroughs in our DSA Course

Explore step-by-step solutions with 4-language code flaps (Java, C#, TS, Python) and visual memory dry runs.

primer

Prefix Sum Pattern Primer

View in DSA Path→
problem

Subarray Sum Equals K (Negative Numbers Solution)

View in DSA Path→
problem

Maximum Subarray (Kadane Algorithm)

View in DSA Path→
⚖️What Did I Give Up By Choosing This? (The Tradeoff)

"Sliding window runs with O(1) auxiliary space but demands strict monotonicity (non-negative elements). Prefix sum with a hash map handles negative values and arbitrary integers, but trades away O(1) space for O(N) map storage and hash collision overhead."

Practice Real Indian Hiring Loops

See the exact problems asked at Flipkart, Swiggy, Razorpay, PhonePe, and Amazon with verified candidate reports and round structures.