Bitpath

Lesson 2 · Unit 03

Subarray sum equals K

Count runs with a given sum using prefix totals in a map

12 exercisesabout 3 min

What you practise

  • Prefix counts in a map
  • Why it starts with {0: 1}

Try a question from this lesson

Pick one

Walking a list, your running total is now 17. You want a run of neighbours ending right here that sums to 5. Which earlier running total proves one exists?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Count the totals you have seen

Walk the list keeping a running total. A run ending here sums to k exactly when some earlier running total equals total - k.

So keep a map from each running total to how often it has occurred, and add that count at every step. It starts with the total 0 seen once: the empty start of the list.

from collections import defaultdict

def count_k(nums, k):
    seen = defaultdict(int)
    seen[0] = 1
    total = count = 0
    for x in nums:
        total += x
        count += seen[total - k]
        seen[total] += 1
    return count
function countK(nums, k) {
  const seen = new Map();
  seen.set(0, 1);
  let total = 0, count = 0;
  for (const x of nums) {
    total += x;
    count += seen.get(total - k) ?? 0;
    const had = seen.get(total) ?? 0;
    seen.set(total, had + 1);
  }
  return count;
}
function countK(
  nums: number[],
  k: number,
): number {
  const seen = new Map<number, number>();
  seen.set(0, 1);
  let total = 0, count = 0;
  for (const x of nums) {
    total += x;
    count += seen.get(total - k) ?? 0;
    const had = seen.get(total) ?? 0;
    seen.set(total, had + 1);
  }
  return count;
}

Python notedefaultdict(int) is a dict that hands back 0 for a missing key instead of raising KeyError, so seen[x] += 1 works the first time.

JavaScript noteA Map keeps numbers as numbers. A plain object would turn the keys into strings, which works here but is easy to trip over.

TypeScript notenew Map<number, number>() fixes the key and value types. seen.get(...) returns number | undefined, so ?? 0 is required before adding.

10 more exercises in the app

  • 3× type the answer
  • 4× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy