download

Count subarrays that sum to k when numbers can be negative

Algorithms~15 minReviewed 1 Nov 2026Free · No sign-in

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).

"PYTHON"
count_sum_k([2, -1, 3, -2, 1, 2], 2)  # 5
count_sum_k([1, -1, 0], 0)            # 3
"CODE · PYTHON"
def count_sum_k(changes, k):
    ...
Show hints (3)
  1. "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.

  2. "RUNNING TOTALS"

    Keep a running total. The sum of days i to j is the total after day j minus the total before day i. For it to equal k, that earlier total must be total - k.

  3. "COUNT, THEN ADD"

    Keep a Counter of the totals seen so far. Start it with {0: 1}, the total before day 0. On each day, first add seen[total - k] to the answer, then do seen[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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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.

daychangetotallooks forfoundcount
02201 (the start)1
1-11-101
23421 (after day 0)2
3-2201 (the start)3
41311 (after day 1)4
52531 (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 = 0 every 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] with k = 0 gives 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 day j, if total - k first appeared after day i, the period has j - i days. 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 positive k, Python's % never returns a negative number, so -1 % 5 is 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 →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.