Python coding

Count runs that sum to k

Given a list of integers nums (it may contain negatives and zeros) and an integer k, return how many non-empty contiguous subarrays have a sum of exactly k. Subarrays at different positions count separately, even when they hold the same values.

Aim for one pass over nums.

Besides the tests, one large input (6,000 numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_runs([1,1,1], 2) → 2
  • count_runs([1,2,3], 3) → 2
  • count_runs([1,-1,0], 0) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

With running prefix sums, the sum of nums[i:j] is P[j] - P[i]. A subarray ending here sums to k when an earlier prefix equals P - k.

Hint 2

Keep a map from each prefix value to how many times it appeared, seeded with {0: 1}. Add counts[prefix - k] before recording the current prefix.

Solution and why it works
pythonO(n) · O(n)
def count_runs(nums: list[int], k: int) -> int:
    counts = {0: 1}
    prefix = total = 0
    for x in nums:
        prefix += x
        total += counts.get(prefix - k, 0)
        counts[prefix] = counts.get(prefix, 0) + 1
    return total

A subarray ending at the current index sums to k exactly when some earlier prefix equals prefix - k, so a map of prefix counts answers it in O(1). Seed it with {0: 1}, the empty prefix, or you miss every subarray that starts at index 0. A sliding window fails here: with negatives, shrinking the window does not lower the sum.

Related lab: Loops in motion