Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals k.
Many people try to use a Sliding Window / Two Pointers approach, but it fails whenever the array contains negative numbers. Why does the sliding window fail, and how does the Prefix Sum Frequency Hash Map solve it in O(N) time?
This is a classic trap that catches even intermediate developers. Let’s see why two pointers collapse and why prefix math is the ultimate solution.
1. Why Two Pointers Fails on Negative Numbers
A sliding window relies on a fundamental monotonic invariant:
The moment you introduce negative numbers, this invariant is destroyed! Expanding the right pointer might add
-10, making the sum smaller. Shrinking the left pointer might drop-5, making the sum larger. You can no longer make greedy left/right decisions!2. The Prefix Sum Invariant
Let
prefix[i]be the cumulative sum from index 0 toi.The sum of any contiguous subarray from index
j + 1toiis given by:sum(j+1 ... i) = prefix[i] - prefix[j].We want this subarray sum to equal
k:The Breakthrough: As you iterate through the array maintaining a running prefix sum
curr_sum, you simply ask the hash map: ‘How many times have we already seen a prefix sum equal tocurr_sum - kin the past?’Every time you find that value in the hash map, you have found a valid subarray that sums exactly to
k!Clean Python 3.12 Implementation
Why prefix_counts[0] = 1 is Critical
If you forget
prefix_counts[0] = 1, any subarray that starts at index 0 and sums tok(e.g.nums = [3, ...], k = 3) will producecurr_sum = 3, and look forcurr_sum - k = 0in the map. Without the base case, it would fail to count that valid subarray!Complexity Breakdown
O(N). Single pass through the array withO(1)hash map lookups.O(N)to store prefix sum frequencies.