Count the stretches of numbers that add up to k, negatives included. Keep a running total and a tally of totals seen, and look up the one that's k behind.
▼The problem
LeetCode 560 (Medium). Given an integer array nums (values can be negative or zero) and an integer k, return how many contiguous subarrays sum to exactly k.
Example: nums = [1, 2, -2, 1, 1, 1], k = 3 → 4: [1, 2], [1, 2, -2, 1, 1], [2, -2, 1, 1, 1] and [1, 1, 1].
def subarray_sum(nums, k):
count = {0: 1} # altitude -> visits
total = answer = 0
for x in nums:
total += x
answer += count.get(total - k, 0)
count[total] = count.get(total, 0) + 1
return answerTRY IT ON LEETCODE ▶The solution
def subarray_sum(nums, k):
count = {0: 1} # altitude -> visits
total = answer = 0
for x in nums:
total += x
answer += count.get(total - k, 0)
count[total] = count.get(total, 0) + 1
return answerTranscript
Subarray Sum Equals K. You get a list of whole numbers, some of them negative, and a target k. Count the stretches of neighbors that add up to exactly k.
Take one, two, minus two, one, one, one, with k equal to three. Four stretches work: one and two at the start, the last three ones, and two longer ones that run across the minus two.
The simple way tries every start and every end. Six numbers already give twenty-one stretches; in general, that's n squared. And a sliding window fails: a negative number shrinks the sum as the window grows, so you never know which way to move.
Instead, think of a hike. Each number is a step up or down, and your altitude is the running total. A stretch's sum is how far you climbed across it: the altitude at its end, minus the altitude at its start. So it sums to k exactly when today's altitude is k above an earlier one.
So at each step, ask: how often have I stood at my altitude minus k? Keep a logbook of the altitudes you've visited, starting with zero, seen once, so stretches that begin at the very start count too.
In code, the logbook is a hash map from altitude to visits. For each number, add it to the total, add the visits at total minus k to the answer, then log the total.
Let's hike. Up one, to one: we need minus two, never seen. Up two, to three: we need zero, logged once, so one stretch. Down two, back to one. Up to two: nothing at minus one. Up to three: zero again, two stretches. Up to four: we need one, and we've stood there twice. Two ropes at once: four in all.
One pass, with constant work per step, so the time is linear. The logbook holds at most n plus one altitudes, so the space is linear too.
Track the running total, and look back k. That's Subarray Sum Equals K.