Skip to content
BytePatterns

Subarray Sums With a Map

Hash Tables: lesson 6 of 8

The complement trick, moved onto running totals.

Lesson 6 of 8 · 6 min

Subarray Sums With a Map

Step 1 of 7

Two Sum asks a map for a complement. Do the same with running totals — starting with the empty one.

The Idea

Two Sum asks a map for the complement of a value. Do the same with running totals. A subarray ending here sums to k exactly when some earlier prefix total equals running - k. So carry the running total, ask the map how many times that complement has already been seen, add it to the answer, and record the current total for the positions still to come. One pass, and negative numbers do not bother it.

Real-World Example

A bank statement and the question "how many stretches of days net exactly 100?". Running balances answer it: on each day, look up how often the balance once stood 100 lower. Every match marks a stretch that gained precisely that amount.

The Code

def count_subarrays(nums, k):
    seen = {0: 1}          # the empty prefix counts once
    total = running = 0
    for x in nums:
        running += x
        total += seen.get(running - k, 0)      # prefixes that close a k-sum
        seen[running] = seen.get(running, 0) + 1
    return total

print(count_subarrays([1, 2, 3, -2, 2], 3))   # 4

Python

Your turn

Fill in the blank.

seen = {0: 1}
total = running = 0
for x in nums:
  running += x
  total += seen.get(___, 0)
  seen[running] = seen.get(running, 0) + 1

Mini quiz

1 / 3

Why does the map start out holding {0: 1}?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.