Algorithmic patterns · 2 / 15 Theory

Prefix sums

If you are going to answer many sum queries over ranges of the same list, do not recompute each time: precompute the prefix sums (the running sum up to each position) and each query costs a subtraction.

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

prefixes = [0]
for x in numbers:
    prefixes.append(prefixes[-1] + x)
print(prefixes)                          # [0, 3, 4, 8, 9, 14, 23, 25, 31]

def range_sum(left, right):                # sum of numbers[left..right], both included
    return prefixes[right + 1] - prefixes[left]

print(range_sum(2, 4))                  # 10   (4 + 1 + 5)

from itertools import accumulate
print(list(accumulate(numbers)))         # [3, 4, 8, 9, 14, 23, 25, 31]

prefixes[i] is the sum of the first i elements, which is why it starts with a 0, and the sum of the range [left, right] is prefixes[right + 1] - prefixes[left].

Prefixes and dictionaries: counting ranges with sum k

A range (a, b] adds up to k if prefix[b] - prefix[a] == k. Walking the list with a dictionary that counts how many times each running sum has appeared, all ranges are counted in O(n). It also works with negative numbers, which a sliding window does not allow.

def count_subarrays(numbers, k):
    seen = {0: 1}          # how many times each running sum has appeared
    running = 0
    total = 0
    for x in numbers:
        running += x
        total += seen.get(running - k, 0)   # ranges ending here that add up to k
        seen[running] = seen.get(running, 0) + 1
    return total

print(count_subarrays([1, 2, 3, -3, 3], 3))   # 5

You practice it in Range sums with prefixes and Subarrays with sum k.