Count Subarrays
A subarray is a non-empty stretch of neighbouring items of a list, such as the 2nd, 3rd and 4th items.
Write count_subarrays(nums, k) that returns how many subarrays of nums add up to exactly k. The list may contain negative numbers and zeros. Two subarrays in different places count separately, even if they contain the same numbers.
Understand the problem
Count by hand first.
How many subarrays of [1, 1, 1] add up to 2?
The subarrays are the first two items and the last two items: [1, 1] twice, in different places. Both count. [1, 1, 1] adds to 3, so it does not.
How many subarrays does a list of 4 items have? (Count every stretch of neighbouring items, of any length.)
By length: 4 of length 1, 3 of length 2, 2 of length 3 and 1 of length 4, which is 10. For n items it is n x (n + 1) / 2.
How many subarrays of [0, 0, 0] add up to 0?
All 6 of them: three of length 1, two of length 2 and one of length 3. Zeros are the case that people undercount.
Try examples by hand
Look for a way to express the sum of a stretch.
Let P[i] be the sum of the first i items (P[0] is 0). What is the sum of the items from position i up to (not including) position j?
P[j] + P[i]P[j] - P[i]P[j] x P[i]
The sum of the first j items minus the sum of the first i items is exactly the items in between. Sums of stretches are differences of running totals.
A friend suggests a sliding window: grow the window while the sum is below k, shrink it when the sum is above k. Why does this fail when negative numbers are allowed?
- It is too slow
- A negative number can bring the sum back down, so a sum above k does not mean you should shrink
- It uses too much memory
The window method needs "adding items only increases the sum". With negative numbers a too-large sum can still become exactly k after more items. So you need another approach.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def count_subarrays(nums, k):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
How can you visit every subarray exactly once?
Hint 2: the shape of the answer
For each start position, keep a running total and extend the end one item at a time. Each time the total equals k, add one to the count.
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
The stretch from i to j adds to k when P[j] - P[i] == k. For a fixed j, which earlier running total P[i] are you looking for?
P[j] + kP[j] - kk
From P[j] - P[i] = k you get P[i] = P[j] - k. So for each position you only need to know how many earlier running totals equal P[j] - k.
Which structure can answer "how many earlier running totals equal this value?" quickly?
- A list
- A dictionary from running total to how many times it has occurred
- A set
You need a count, not just yes or no: several earlier positions can have the same running total, and each gives a different subarray. A set only remembers yes or no, so it would undercount.
Before reading any item, the running total is 0. Why must the dictionary start with {0: 1}?
- It does not need to
- So that subarrays starting at the very first item can be found
- To avoid an error
A subarray that starts at the first item has P[i] = 0 (nothing before it). Without recording "total 0 has occurred once", those subarrays are never counted.
Make it faster
Now write the version that reads the list once.
def count_subarrays(nums, k):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
Can you count, for each position, how many subarrays end there and add up to k?
Hint 2: the pattern
Running total plus a dictionary of how many times each running total has occurred (start it with {0: 1}).
Hint 3: pseudocode
seen = {0: 1} (running total -> how many times)
total = 0
count = 0
for each x:
total += x
count += seen.get(total - k, 0) # earlier totals that make a stretch of sum k
seen[total] = seen.get(total, 0) + 1
return count
Order matters: look up total - k before you add the new total.
Reflect
Brute force: O(n squared)
def count_subarrays(nums, k):
count = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
count += 1
return count
Improved: O(n) with prefix sums
def count_subarrays(nums, k):
seen = {0: 1}
total = 0
count = 0
for x in nums:
total += x
count += seen.get(total - k, 0)
seen[total] = seen.get(total, 0) + 1
return count
Pattern: prefix sums plus a dictionary. Write the sum of any stretch as a difference of two running totals, then turn "find a start that gives the right difference" into one dictionary lookup. This idea ("prefix sum + hash map") appears in many interview problems: subarray sums, balanced counts, equal numbers of two things.
Why not a set? Several earlier positions can share the same running total, and each one is a different subarray. The dictionary stores how many, which is what is being counted.
Cost:
| Version | Time | Extra space |
|---|---|---|
| Every start and end | O(n squared) | O(1) |
| Prefix sums and dictionary | O(n) | O(n) |
What an interviewer might ask next: The same problem but you must return the longest subarray that adds to k. What would you store in the dictionary instead of a count? (The first position where each running total appeared.)
import random
VISIBLE = 3
CASES = [
(([1, 1, 1], 2), 2, 'two separate places'),
(([1, 2, 3], 3), 2, '[1, 2] and [3]'),
(([0, 0, 0], 0), 6, 'zeros'),
(([], 0), 0, 'empty list'),
(([3], 3), 1, 'a single item'),
(([5], 1), 0, 'nothing adds up'),
(([1, -1, 1, -1], 0), 4, 'negative numbers'),
(([3, 4, 7, 2, -3, 1, 4, 2], 7), 4, 'a mix of numbers'),
(([2, 2, 2, 2], 4), 3, 'overlapping subarrays'),
]
def REFERENCE(nums, k):
seen = {0: 1}
total = count = 0
for x in nums:
total += x
count += seen.get(total - k, 0)
seen[total] = seen.get(total, 0) + 1
return count
LIMIT = 2.0
def PERF():
rng = random.Random(9)
nums = [rng.randint(-5, 5) for _ in range(15000)]
more = [rng.randint(-5, 5) for _ in range(200000)]
return [('15000 numbers', (nums, 5)), ('200000 numbers', (more, 5))]