Python 3D Academyবাংলা

Prefix sums with a dict: runs that add up to k

🌍 In real life. Your bKash wallet goes up and down every day: +500 from a tuition job, −300 for groceries, +200, −400… On how many stretches of days did your money come back to exactly where it started? That happens exactly when the balance at the end of a stretch equals the balance just before it began. So as you read each day's balance, ask: "how many times have I seen this balance before?" A notebook of balances seen so far answers it at once.

The idea in one sentence: a run nums[i:j] adds up to k exactly when prefix[j] - prefix[i] == k, that is, when an earlier running total equals prefix[j] - k; so count, in a dict, how often each running total has appeared.

Its words:

  • running total: the sum of every number so far, also called a prefix sum
  • subarray: a run of items next to each other, nums[i:j]
  • seen counts: a dict from each running total to how many times it has appeared

How it works, step by step:

  1. seen = {0: 1}: the running total before any number is 0, seen once
  2. for each number: total += x
  3. the runs ending here that add up to k are as many as the earlier totals equal to total - k: count += seen.get(total - k, 0)
  4. then record this total: seen[total] = seen.get(total, 0) + 1

Watch the purple line mark the total we are looking for, and the earlier towers at that height light up:

Why it is correct. Each run is counted exactly once: at its right end j, by the earlier total prefix[i] that starts it. Because we look up total - k before adding the current total, a run is never matched with itself (an empty run).

Why not a sliding window? With negative numbers the rule isn't monotone (Chapter 37.4): adding −3 can bring a sum back down to k. Prefix sums don't care about signs.

What it costs, worked out. One pass, one dict lookup and one update per number: O(n) time and O(n) memory. Checking every run is n(n + 1)/2 sums: for 10,000 numbers, about 50 million against 10,000 lookups.

def count_subarrays(nums, k):
    seen = {0: 1}
    total = count = 0
    for x in nums:
        total += x
        count += seen.get(total - k, 0)    # runs ending here
        seen[total] = seen.get(total, 0) + 1
    return count

wallet = [500, -300, 200, -400, 300, -300]
print(count_subarrays(wallet, 0))           # stretches with no net change
print(count_subarrays([1, 2, 3, -3, 3], 3))

Mistakes and edge cases.

  • starting with seen = {} instead of {0: 1} misses every run that starts at position 0
  • recording seen[total] before the lookup counts empty runs when k is 0
  • += 1 instead of += seen.get(...): several earlier totals can match, and each one is a different run
  • for the longest run with sum k, store the first position of each total instead of a count, and never overwrite it

Quiz

  1. What does this print?

    seen = {0: 1}
    total = count = 0
    for x in [1, 1, 1]:
        total += x
        count += seen.get(total - 2, 0)
        seen[total] = seen.get(total, 0) + 1
    print(count)
  2. Why does seen start as {0: 1}?

    • It stands for the running total before any number, so runs starting at position 0 are found
    • Dicts can't start empty
    • It counts the zeros in the list
  3. Why can't a sliding window count runs that add up to k when numbers can be negative?

    • Growing can lower the sum, so a window that is too big may still become exactly k
    • Windows can't hold negative numbers
    • It can; it is just slower
  4. count_subarrays([0, 0], 0) should be 3 ([0], [0], [0, 0]) but this gives 5. Which line is in the wrong place?

    def count_subarrays(nums, k):
        seen = {0: 1}
        total = count = 0
        for x in nums:
            total += x
            seen[total] = seen.get(total, 0) + 1
            count += seen.get(total - k, 0)
        return count

Coding tasks

  1. Write count_subarrays(nums, k) in O(n) with prefix sums and a dict: how many runs of neighbours (at least one number long) add up to k. Numbers can be negative.

  2. Write longest_zero_sum(nums) in O(n): the length of the longest run of neighbours that adds up to 0 (0 if there is none). Remember where each running total first appeared.