Learn / Arrays

Prefix sums and difference arrays

Store running totals once, and the sum of any subarray becomes one subtraction. Remember earlier running totals in a hash map, and "how many subarrays sum to k?" becomes a single pass.

How to recognise it

  • The question is about subarrays (contiguous pieces) and their sums, counts or lengths.
  • It asks for the sum of many ranges, which would mean adding the same elements again and again.
  • The array can contain negative numbers, so a sliding window that only grows and shrinks will not work.
  • XOR or product instead of sum, with the same "everything from i to j" shape.
  • Many updates of the form "add v to every element from l to r" (a difference array).

The idea in one picture

Think of a car's odometer. To know how far you drove between the 2nd and 5th stops, you do not add up every metre in between; you read the odometer at both stops and subtract. A prefix sum array is that odometer for an array: the running total up to each position.

prefix[0] = 0
for i from 0 to n - 1:
    prefix[i + 1] = prefix[i] + nums[i]

sum of nums[l..r] = prefix[r + 1] - prefix[l]     # one subtraction

Counting subarrays with a hash map

A subarray ending at i sums to k exactly when some earlier running total equals running - k. So walk once, and keep a map of how many times each running total has appeared:

seen = {0: 1}                     # the empty prefix
running = 0
for x in nums:
    running = running + x
    count = count + seen[running - k]
    seen[running] = seen[running] + 1

Variants change only what the map stores or what you look up:

QuestionMap storesLook up
How many subarrays sum to k?running total → how many timesrunning - k
Longest subarray with sum k?running total → first indexrunning - k
Any subarray with sum 0?set of running totalsrunning itself
How many subarrays have XOR k?running XOR → how many timesrunning XOR k

A guided example: how many subarrays of [1, 1, 1] sum to 2?

xrunninglook up running - 2foundcountseen afterwards
(start)00{0: 1}
11-10 times0{0: 1, 1: 1}
1201 time1{0: 1, 1: 1, 2: 1}
1311 time2{0: 1, 1: 1, 2: 1, 3: 1}

The answer is 2: [1, 1] twice.

Prefix products and difference arrays

The same "precompute from the left" idea works with products. For each position, the product of everything to its left times the product of everything to its right gives "the product of all others" without division.

A difference array is the reverse trick, for updates: to add v to every element from l to r, add v at l and subtract it at r + 1. After all updates, one running sum turns the differences back into the final array.

Common mistakes

  • Forgetting the starting entry for the empty prefix, which misses subarrays that begin at index 0.
  • For the longest subarray, overwriting the stored index with later ones. Keep the first index only.
  • Adding the current running total to the map before looking up, which can match a subarray of length 0.
  • Using a 32-bit running total when long arrays of large values can overflow it.

Problems

0 of 6 solved

Check yourself

With prefix[0] = 0 and prefix[i + 1] = prefix[i] + nums[i], what is the sum of nums[l..r]?

While walking the array, the running sum is 12 and k = 5. Which earlier running sum would mean a subarray ending here sums to 5?

Why start the map with the running sum 0 already in it?

Arrays with negative numbers. Why does a two-pointer sliding window fail for "subarray sum equals k" here, while prefix sums work?