Prefix sums

A prefix sum is the running total: prefix[i] is the sum of the first i numbers. The sum of nums[a:b] is then prefix[b] - prefix[a], one subtraction instead of a loop. Building it is O(n), and itertools.accumulate does it for you.

The signal: sums over many subarrays or ranges.

To count subarrays that sum to k, walk the list keeping the running total. A subarray ending here sums to k when some earlier prefix equals total - k. Count earlier prefixes in a dict, starting with {0: 1} for the empty prefix. That is O(n) time, versus O(n²) for trying every start and end.

A common mistake: using a sliding window. Windows only work when all numbers are positive. With negatives, a bigger window can have a smaller sum.

Exercise: finish count_subarrays so it returns how many contiguous, non-empty subarrays of nums sum to k. Press Check to run the tests.