Count subarrays that sum to k when numbers can be negative
Question
A shop logs the daily stock change for one item. Some days are negative. Count the periods of one or more days in a row whose changes add up to exactly k. Two periods are different if they start or end on different days. Aim for O(n).
count_sum_k([2, -1, 3, -2, 1, 2], 2) # 5 count_sum_k([1, -1, 0], 0) # 3
def count_sum_k(changes, k): ...
Show hints (3)
- "WHY NOT A WINDOW"
With only positive numbers you could grow and shrink a window. Here a negative day can make a longer period smaller again, so there is no clear rule for moving the left edge.
- "RUNNING TOTALS"
Keep a running total. The sum of days
itojis the total after dayjminus the total before dayi. For it to equalk, that earlier total must betotal - k. - "COUNT, THEN ADD"
Keep a
Counterof the totals seen so far. Start it with{0: 1}, the total before day 0. On each day, first addseen[total - k]to the answer, then doseen[total] += 1.
Show checked explanation
Keep a running total and a Counter of the totals seen so far, starting with {0: 1}. A period that ends today sums to k when an earlier total equals total - k, so add that count to the answer. Only then record today's total. One pass: O(n) expected time and O(n) memory.
from collections import Counter def count_sum_k(changes, k): seen = Counter({0: 1}) # the total before day 0 total = count = 0 for change in changes: total += change count += seen[total - k] # look up first seen[total] += 1 # then record return count print(count_sum_k([2, -1, 3, -2, 1, 2], 2)) print(count_sum_k([1, -1, 0], 0)) print(count_sum_k([], 0))
5 3 0
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is [2, -1, 3, -2, 1, 2] with k = 2. On each day the code looks for earlier totals equal to total - 2.
| day | change | total | looks for | found | count |
|---|---|---|---|---|---|
| 0 | 2 | 2 | 0 | 1 (the start) | 1 |
| 1 | -1 | 1 | -1 | 0 | 1 |
| 2 | 3 | 4 | 2 | 1 (after day 0) | 2 |
| 3 | -2 | 2 | 0 | 1 (the start) | 3 |
| 4 | 1 | 3 | 1 | 1 (after day 1) | 4 |
| 5 | 2 | 5 | 3 | 1 (after day 4) | 5 |
Each match is one period. It starts the day after the matching total and ends today:
- day 0 alone: 2;
- days 1 to 2: -1 + 3;
- days 0 to 3: 2 - 1 + 3 - 2;
- days 2 to 4: 3 - 2 + 1;
- day 5 alone: 2.
That is 5 periods.
The {0: 1} entry is the total before the first day, not an empty period. It lets a period that starts on day 0 match like any other: day 0 and days 0 to 3 above.
Why a Counter and not a set? The same total can appear more than once, and each time is a different start. In [1, -1, 0] with k = 0, the totals are 1, 0 and 0. On day 2 the code looks for 0 and finds it twice: the start and the total after day 1. Those are two periods, days 0 to 2 and day 2 alone.
Each day does one dictionary lookup and one update, O(1) on average. So the pass is O(n) expected time.
Common mistakes
- Using a sliding window. It assumes that a longer period never has a smaller sum, and negative days break that. A typical shrink-when-too-big window finds only 2 of the 5 periods in the first example.
- Recording today's total before the lookup. With
k = 0every day then matches itself, an empty period.[1, -1, 0]gives 6 instead of 3. - Starting with an empty
Counter. A period that starts on day 0 has no earlier total to match, so the first example gives 3 instead of 5. - Keeping the totals in a set. Equal totals merge into one, so periods are lost.
[1, -1, 0]withk = 0gives 2 instead of 3.
Follow-up questions
- "Now find the longest period that sums to k." Store the first day each total appears, starting with
{0: -1}, and never overwrite it. On dayj, iftotal - kfirst appeared after dayi, the period hasj - idays. In the first example the longest is days 0 to 3: 4 days. - "What if every change is above zero?" Then a longer period always has a bigger sum, so a sliding window works. Add days on the right. While the sum is above
k, drop days on the left. That needs O(1) memory instead of O(n). - "Count the periods whose sum is divisible by k." Count remainders instead of totals: look up and record
total % k, starting with{0: 1}. For a positivek, Python's%never returns a negative number, so-1 % 5is 4. In some languages you must fix the sign yourself.
What a strong answer covers
Explains why a window fails with negative numbers. Writes a period's sum as the difference of two running totals, starts the counter with {0: 1} and looks up before recording. Tests k = 0 and an empty list, and says O(n) is expected time because it relies on hashing.
Open in interactive practice deck →