awelgorithms

// learn

Prefix sums and difference arrays

A prefix sum array stores running totals: prefix[i] is the sum of the first i values. After one O(n) pass, the sum of any range [l, r) is prefix[r] - prefix[l], a single subtraction instead of a loop.

Updated

The same idea runs the other way as a difference array, which applies many range updates in O(1) each, and combines with a hash map to count subarrays with a given sum, even when values are negative and a sliding window can't be used.

When to use it

The template

def subarray_sum_equals_k(nums, k):
    seen = {0: 1}               # prefix sum -> how many times it occurred
    total = count = 0
    for x in nums:
        total += x              # prefix sum up to and including x
        count += seen.get(total - k, 0)  # prefixes that leave exactly k
        seen[total] = seen.get(total, 0) + 1
    return count

# range sum [l, r) with prefix = [0, a0, a0+a1, ...]: prefix[r] - prefix[l]

The variants you will meet

Building and querying

Start the prefix array with a 0 so prefix[i] is the sum of the first i items and every range [l, r) is prefix[r] - prefix[l]. The extra leading zero removes all the off-by-one special cases.

Counts, products, XOR and balance

Anything you can accumulate and undo works the same way: counts of values matching a test, XOR of a range, a +1/-1 balance for equal zeros and ones. Products need care, because a zero can't be divided out.

Prefix sums with a hash map

A subarray sums to k exactly when two prefix sums differ by k. Count earlier prefixes in a map as you go: Subarray Sum Equals K, subarrays divisible by k, and splitting an array into equal halves.

Difference arrays

To add v to every item in [l, r], add v at l and subtract it at r + 1; one prefix pass at the end rebuilds the array. Thousands of overlapping updates cost O(1) each.

2D prefix sums

In a grid, each cell stores the sum of the rectangle above and to its left. Any rectangle's sum is then four lookups combined by inclusion and exclusion, and difference arrays extend to 2D the same way.

Time and space complexity

Building the prefix array is O(n) time and O(n) space; each range query is then O(1). Subarray sum equals k is O(n) time and O(n) space for the map. A 2D table is O(m·n) to build with O(1) rectangle queries.

check which skills you have 10 minutes, free, no account.

All 15 lessons, in order

Common questions

When should I use prefix sums instead of a sliding window?

When values can be negative, or when you need to count every subarray with an exact sum. A sliding window relies on shrinking always moving you toward valid, which negative numbers break; prefix sums with a hash map don't depend on that.

Why does the hash map start with {0: 1}?

It stands for the empty prefix before the first element. Without it, a subarray that starts at index 0 and sums to k would never be counted, because there would be no earlier prefix to subtract.

What is a difference array?

The array of differences between neighbours, d[i] = a[i] - a[i-1]. Adding v to a whole range of a changes only two entries of d, and a prefix sum over d gives a back. It is the inverse of a prefix sum.

Do prefix sums work if the array changes?

Not efficiently: one update changes every later prefix, O(n). For many updates mixed with queries, use a Fenwick tree (binary indexed tree) or a segment tree, which do both in O(log n).

Other guides