Skip to content
mlmentorship

Subarray Sum Equals K

Count continuous subarrays whose sum equals the target.

Published · 13 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Subarray Sum Equals K

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list nums and an integer target. Output. Return the number of nonempty contiguous subarrays whose sum equals target. Rules. Count ranges by their start and end positions; overlapping ranges and identical value sequences count separately. Negative values, zeros, and duplicates are allowed. Do not count the empty range, even for target zero. Leave the input unchanged. Empty input returns zero. Example. [1, -1, 1, -1, 1] with target zero returns 6. The valid ranges have lengths two or four. For [1, 1, 1] and target 2, return 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Count earlier prefix sums equal to current prefix minus target.

Problem trace

Count earlier matching prefixes before storing the current prefix

Input and goalCount continuous subarrays whose sum equals the target.
Seed the empty prefixUse nums = [1, -1, 1, -1, 1] and target 0. Record the empty boundary once so ranges starting at index 0 can match.
next i=010-1112-1314
mapLabelearlier prefix countsprefix0target0answer0
earlier prefix counts0count 1
key 0
count 1
next i
0
prefix
0

Recognize it
The task counts contiguous ranges with an exact sum, values may be negative, and many ranges can end at the same index, so a monotone sliding window is unsafe.
Keep true
Before processing nums[i], the map counts every prefix ending before i. After prefix is updated, count(prefix - target) is exactly the number of valid subarrays ending at i; only then is the current prefix inserted.
Reuse it
Rewrite a range equation as current prefix minus earlier prefix. Store counts when duplicate earlier states represent distinct starts; this also transfers to subarray sums divisible by k and equal-count prefix signatures.
Use nums = [1, -1, 1, -1, 1] and target 0. Record the empty boundary once so ranges starting at index 0 can match. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does index 3 add two ranges? Why must the current prefix be stored only after the lookup?
Full interview answer 13 min read

Count the nonempty contiguous ranges whose values add to a requested target sum.

Problem

Input. An integer list nums and an integer target.

Output. Return the number of nonempty contiguous subarrays whose sum equals target.

Rules. Count ranges by their start and end positions; overlapping ranges and identical value sequences count separately. Negative values, zeros, and duplicates are allowed. Do not count the empty range, even for target zero. Leave the input unchanged. Empty input returns zero.

Example. [1, -1, 1, -1, 1] with target zero returns 6. The valid ranges have lengths two or four. For [1, 1, 1] and target 2, return 2.

Picture

Put a boundary before the array and after each element. Write the total so far at each boundary: 0, 1, 0, 1, 0, 1. Two equal totals enclose a zero-sum range. Their positions determine its start and end.

Problem trace

Separate zero-target case: query earlier prefixes before storing the current one

Worked example: query the old prefix frequency before inserting the current prefixFor input (0) and target 0, the seeded empty prefix contributes one matching subarray. Inserting the current prefix first would incorrectly count two.The query sees only the earlierstate; insertion happens afterwardQuery seeded prefix zero beforeinserting this zero00:1One seeded match contributes exactlyone subarray.Then insert this prefix; do notrepeat its query00:2Stored frequency becomes two; theanswer remains one.
Read it this way: For input (0) and target 0, the seeded empty prefix contributes one matching subarray. Inserting the current prefix first would incorrectly count two. Which spurious extra match appears if the current zero prefix is inserted before its query?
Reference drawing

Problem trace

Count earlier matching prefixes before storing the current prefix

Worked example: query the old prefix frequency before inserting the current prefixFor input (0) and target 0, the seeded empty prefix contributes one matching subarray. Inserting the current prefix first would incorrectly count two.The query sees only the earlierstate; insertion happens afterwardQuery seeded prefix zero beforeinserting this zero00:1One seeded match contributes exactlyone subarray.Then insert this prefix; do notrepeat its query00:2Stored frequency becomes two; theanswer remains one.
Execution trace
Input and goalCount continuous subarrays whose sum equals the target.
Seed the empty prefixUse nums = [1, -1, 1, -1, 1] and target 0. Record the empty boundary once so ranges starting at index 0 can match.
next i=010-1112-1314
mapLabelearlier prefix countsprefix0target0answer0
earlier prefix counts0count 1
key 0
count 1
next i
0
prefix
0

Recognize it
The task counts contiguous ranges with an exact sum, values may be negative, and many ranges can end at the same index, so a monotone sliding window is unsafe.
Keep true
Before processing nums[i], the map counts every prefix ending before i. After prefix is updated, count(prefix - target) is exactly the number of valid subarrays ending at i; only then is the current prefix inserted.
Reuse it
Rewrite a range equation as current prefix minus earlier prefix. Store counts when duplicate earlier states represent distinct starts; this also transfers to subarray sums divisible by k and equal-count prefix signatures.
Use nums = [1, -1, 1, -1, 1] and target 0. Record the empty boundary once so ranges starting at index 0 can match. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does index 3 add two ranges? Why must the current prefix be stored only after the lookup?
Read it this way: For input (0) and target 0, the seeded empty prefix contributes one matching subarray. Inserting the current prefix first would incorrectly count two. Which spurious extra match appears if the current zero prefix is inserted before its query?

At a current total prefix, a valid start has total prefix - target. prefix_count stores how many earlier boundaries have each total.

Element indexCurrent totalEarlier matchesNew answer
0100
1011
2112
3024
4126

The initial {0: 1} represents the boundary before index 0. Query before inserting the current boundary. Otherwise, target 0 would count an empty range. Each range is counted once, at its right boundary. Negative values do not change this subtraction rule.

Code

def subarray_sum(nums: list[int], target: int) -> int:
   prefix_count = {0: 1}
   prefix = 0
   answer = 0

   for num in nums:
      prefix += num
      answer += prefix_count.get(prefix - target, 0)
      prefix_count[prefix] = prefix_count.get(prefix, 0) + 1

   return answer

There are additions and expected constant-time map operations. Time is expected and extra space is under bounded-size integer arithmetic. Python integers do not overflow, but larger integers cost more to add and hash.

Change what the map saves

1. Return the longest range

New task: return the maximum length, not the number of ranges.

Picture and change: for a fixed end, the earliest matching start gives the longest range. Replace counts with earliest indices. Boundary -1 lies before the first element. The whole replacement function follows.

def longest_sum(nums, target):
   earliest = {0: -1}
   prefix = best = 0
   for index, value in enumerate(nums):
      prefix += value
      if prefix - target in earliest:
         best = max(best, index - earliest[prefix - target])
      earliest.setdefault(prefix, index)
   return best

Check: longest_sum([1, -1, 1, -1, 1], 0) returns 4. At index 3, total 0 matches boundary -1, giving length 4. Overwriting earliest[0] would lose that start.

Use when: the result asks for length. The boundary subtraction stays unchanged.

2. Return whether a range exists

New task: return a boolean for any nonempty matching range.

Picture and change: membership is enough. Replace counts with a set and return on the first match. Still query before inserting. The whole replacement function follows.

def has_sum(nums, target):
   seen = {0}
   prefix = 0
   for value in nums:
      prefix += value
      if prefix - target in seen:
         return True
      seen.add(prefix)
   return False

Check: has_sum([], 0) is False; has_sum([1, -1], 0) is True. The second total matches the earlier boundary 0.

Use when: only existence matters. Both alternatives retain expected time and extra space.

Failure case

A set loses repeated starts, so it cannot count all ranges. For [0, 0], the answer is 3, not 2. A sliding window also needs a different proof: later negative values can reduce an oversized sum.

Try a changed result

Why is one saved index enough for the longest range but insufficient for the range count?

Check your answer

Counting needs every distinct start. For a fixed end, maximum length needs only the earliest valid start.