Subarray Sum Equals K solution explained
To count the contiguous subarrays that sum to k, keep a running prefix sum and a hash map from each prefix sum to how many times it has appeared. At each index, every earlier prefix equal to the current prefix minus k marks the start of a subarray ending here with sum k, so add that count, then record the current prefix. Seeding the map with a prefix of 0 seen once makes subarrays that start at index 0 count. This runs in O(n) time and O(n) space, and it works with negative numbers, where a sliding window does not.
By Evin JohnPublished 6 min read
Restating the problem
You get an array of integers, which may include negatives and zeros, and an integer k. Count how many contiguous runs of one or more elements have a sum of exactly k. Different start or end positions count as different runs even when they contain the same values.
| Array | k | Count | The subarrays |
|---|---|---|---|
| [2, 4, -1, 3, -2, 4] | 6 | 3 | [2, 4], [4, -1, 3], [2, 4, -1, 3, -2] |
| [1, -1, 1, -1] | 0 | 4 | [1, -1] twice, [-1, 1], and the whole array |
| [3, 3, 3] | 3 | 3 | Each single 3 |
| [0, 0, 0] | 0 | 6 | Every run: three of length 1, two of length 2, one of length 3 |
| [5] | 5 | 1 | The single element |
What the interviewer is testing
Many candidates reach for a sliding window, because the problem sounds like one. The interviewer is waiting to see whether you notice that negative numbers break the window: growing the window can make the sum smaller, so there is no rule for when to shrink it. The prefix-sum idea, and the reason the map must store counts and not just presence, is what separates a strong answer.
Follow-ups
- All values are positive. A sliding window works and needs O(1) extra space: grow the right end, shrink the left while the sum is too big.
- Return the longest such subarray, not the count. Store the first index where each prefix sum appears, and measure the distance at each match.
- Count subarrays whose sum is divisible by m. Key the map by prefix mod m, adjusted to be non-negative in languages where the remainder can be negative.
- A binary array: count subarrays with equal 0s and 1s. Map 0 to -1 and count subarrays with sum 0.
- A 2D grid: count submatrices with sum k. Fix a pair of rows, collapse the columns into a 1D array, and run this algorithm on it.
Quadratic baseline
Pick each start index and extend the end one step at a time, adding to a running total and counting every time it equals k. Keeping the running total avoids re-summing each subarray from scratch, which would make it cubic. It is O(n²) time and O(1) space, easy to get right, and the natural reference for testing.
def count_subarrays_brute(nums, k):
count = 0
for start in range(len(nums)):
running = 0
for end in range(start, len(nums)):
running += nums[end] # sum of nums[start..end]
if running == k:
count += 1
return countPrefix sums and a hash map
Let P be the sum of everything read so far. The sum of a subarray that ends at the current index and starts after some earlier point equals P minus the prefix at that earlier point. So the subarrays ending here with sum k correspond exactly to earlier prefixes equal to P - k. Keep a map from prefix value to the number of times it has occurred. At each step, add the count for P - k, then record P. Start with {0: 1}, which stands for the empty prefix before the first element, so a run starting at index 0 is counted.
from collections import defaultdict
def subarray_sum(nums, k):
seen = defaultdict(int)
seen[0] = 1 # the empty prefix, so subarrays starting at index 0 count
prefix = 0
count = 0
for x in nums:
prefix += x
count += seen[prefix - k] # earlier prefixes that leave exactly k
seen[prefix] += 1
return countTrace [2, 4, -1, 3, -2, 4] with k = 6. The prefixes are 2, 6, 5, 8, 6, 10. At the first 6, the map holds 0 once, so the count becomes 1: that is [2, 4]. At 8, the prefix 2 was seen once, so the count becomes 2: that is [4, -1, 3]. At the second 6, the empty prefix 0 matches again, giving [2, 4, -1, 3, -2] and a count of 3. At 10, the prefix 4 never appeared. The total is 3, matching the table.
function subarraySum(nums, k) {
const seen = new Map([[0, 1]]);
let prefix = 0;
let count = 0;
for (const x of nums) {
prefix += x;
count += seen.get(prefix - k) || 0;
seen.set(prefix, (seen.get(prefix) || 0) + 1);
}
return count;
}The order of the two map operations matters when k is 0. If you record P before looking up P - k, every index would match itself and count an empty subarray. Looking up first keeps every counted run non-empty.
Complexity
| Approach | Time | Extra space | Handles negatives |
|---|---|---|---|
| Sum every subarray from scratch | O(n³) | O(1) | Yes |
| Running total per start | O(n²) | O(1) | Yes |
| Prefix sums with a count map | O(n) average | O(n) | Yes |
| Sliding window | O(n) | O(1) | No, positives only |
Edge cases
- k = 0, especially with runs of zeros, where the answer grows quadratically with the run length.
- A subarray that starts at index 0, which needs the {0: 1} seed.
- Negative numbers and negative k.
- A single element equal to k.
- No matching subarray at all: return 0.
Mistakes
- Using a sliding window when values can be negative.
- Storing a set of seen prefixes instead of counts, which undercounts when a prefix repeats.
- Forgetting the {0: 1} seed.
- Recording the current prefix before the lookup, which miscounts when k is 0.
- Returning the subarrays instead of the count, or the other way round. Read the question.
Saying it out loud
Fictional example
- Candidate
- A sliding window would be tempting, but values can be negative, so adding an element might lower the sum. There's no safe rule for when to shrink.
- Candidate
- Instead, a subarray's sum is the difference of two prefix sums. A run ending here sums to k exactly when an earlier prefix equals the current prefix minus k.
- Candidate
- So I keep a map of prefix sum to how many times I've seen it, starting with zero seen once. At each step I add the count for prefix minus k, then record the current prefix.
- Candidate
- That's one pass, linear time and linear space.
Related problems
The look-up-the-complement step is the same habit as in Two Sum, just applied to running totals. For a window that does work, see Longest Substring Without Repeating Characters. First Missing Positive and Majority Element are other array questions that reward finding the right invariant.
Preparing with Natively
When the prefix-sum idea will not stick, Natively can read the problem from a screenshot on Mac or Windows and lay out the derivation and code in its overlay, so you can compare it to your attempt line by line. During a spoken mock interview it transcribes the conversation, which makes it easy to check later whether you explained why the sliding window fails. More on the AI interview assistant.
Questions people ask
How do you solve Subarray Sum Equals K in O(n)?
Keep a running prefix sum and a hash map of how many times each prefix has appeared, seeded with {0: 1}. At each index add the count of prefix - k, then record the current prefix.
Why does a sliding window not work for Subarray Sum Equals K?
Values can be negative, so extending the window can lower the sum and shrinking it can raise the sum. Without monotonic sums there is no safe rule for moving the window edges.
Why is the prefix sum map seeded with 0?
The 0 entry stands for the empty prefix before the first element. Without it, subarrays that start at index 0 are never counted.
Why store counts instead of a set of prefix sums?
The same prefix sum can appear at several indices, and each one starts a different subarray. A set would count them once and undercount the answer.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
