Skip to content

Lesson 12 of 40More array patterns

Prefix Sums and Difference Arrays

Answer range-sum questions in O(1), count subarrays with a hash map of prefixes, and apply range updates in O(1) with difference arrays.

16 min read0/5 questions

A product dashboard shows revenue for any date range a user drags across a chart. A billing job applies thousands of "add 10 credits to every account from day 40 to day 90" adjustments overnight. A ride-share service checks whether a car is ever over capacity across a route. All three are the same small idea: store running totals once, then answer each question with a subtraction instead of a loop. You met the basic prefix array in Arrays and Hashing. This lesson starts where that one stopped, with the hash-map trick, its variants, prefix products, 2D sums and the reverse tool, the difference array.

The convention that kills off-by-one bugs

Build the prefix array with one extra slot at the front: prefix[0] = 0 and prefix[i + 1] = prefix[i] + a[i]. Then prefix[i] means "the sum of the first i elements", and the sum of the inclusive range a[l..r] is always:

sum(a[l..r]) == prefix[r + 1] - prefix[l]

Building costs O(n) once. Each query is O(1) after that, however wide the range. With q queries you pay O(n + q) instead of O(n · q).

The extra slot is not decoration. Without it, a range that starts at index 0 needs a special case (prefix[r] with nothing to subtract), and special cases are where interview bugs live. Pick this convention and use it every time, so you never have to think about it under pressure. When a problem gives you 1-based positions, convert them to 0-based on the way in and keep the formula unchanged.

Predict the outputPython

What does this print?

p = [0]
for x in [2, -1, 3, 4]:
  p.append(p[-1] + x)
print(p[4] - p[1])
Need a nudge? Hints walk you through it.

Prefix sum plus a hash map: Subarray Sum Equals K

"Count the subarrays whose sum is exactly k." The array can contain negative numbers. Here is the key rearrangement. A subarray a[j..i] sums to k exactly when prefix[i + 1] - prefix[j] == k, which is the same as prefix[j] == prefix[i + 1] - k. So as you walk left to right with a running total, the question at each step becomes: how many earlier prefixes equal running - k? A hash map from prefix value to count answers that in O(1).

Counting subarrays of [1, 2, 1, -1, 2] that sum to 3
1
0
2
1
1
2
-1
3
2
4
prefix = 0seen = {0: 1}count = 0

Seed the map with {0: 1}. That is the empty prefix, and it lets a subarray that starts at index 0 be counted.

1/6

Two details decide whether your answer is right.

  • Seed {0: 1}. Without it you miss every subarray that starts at index 0. If you forget, [3] with k = 3 returns 0.
  • Count first, then record. Look up prefix - k before adding the current prefix to the map. If you record first and k = 0, every position matches itself and you count empty subarrays.
Python
from collections import defaultdict def subarray_sum(nums, k): seen = defaultdict(int) seen[0] = 1 # the empty prefix: a subarray starting at index 0 prefix = count = 0 for x in nums: prefix += x count += seen[prefix - k] # earlier prefixes that leave exactly k seen[prefix] += 1 # record AFTER counting return count def brute(nums, k): n = len(nums) return sum(1 for i in range(n) for j in range(i, n) if sum(nums[i:j + 1]) == k) assert subarray_sum([1, 1, 1], 2) == 2assert subarray_sum([1, 2, 3], 3) == 2assert subarray_sum([2, -2, 3], 3) == 2 # [2, -2, 3] and [3]assert subarray_sum([1, -1, 1, -1], 0) == 4assert subarray_sum([0, 0, 0], 0) == 6 import randomrandom.seed(1)for _ in range(300): nums = [random.randint(-5, 5) for _ in range(random.randint(0, 12))] k = random.randint(-6, 6) assert subarray_sum(nums, k) == brute(nums, k)print("subarray_sum matches brute force on 300 random arrays")print(subarray_sum([2, -2, 3], 3))
Output
Press Run (⌘ Enter) to see what happens.

The random comparison against a brute force is worth copying into your own practice. It catches the seed and ordering bugs in seconds, and it is how you check a clever solution at work before trusting it.

Why the sliding window fails here

As you saw in Sliding Window, the window shrinks from the left when the sum gets too big. That only works if adding an element never lowers the sum, which means all values are non-negative. With negatives, a window that is "too big" right now can become exactly k after one more element, so moving the left edge forward throws answers away. The prefix-map approach makes no assumption about signs. If the input is guaranteed positive, a window is also O(n) and uses O(1) space, so say both in an interview and pick based on the constraints.

Three variants with one twist each

The same skeleton (running value, hash map keyed by that value, look up before you store) solves a family of problems. Each changes one thing.

Contiguous Array (longest subarray with equal numbers of 0s and 1s). Map every 0 to −1. Now "equal counts" means "sum is 0", and a sum of 0 between two positions means the two prefixes are equal. You want the longest such stretch, so store the first index each prefix appears at and never overwrite it. Seed with {0: -1}, so a balanced prefix from index 0 gives length i - (-1) = i + 1.

Continuous Subarray Sum (is there a subarray of length at least 2 whose sum is a multiple of k?). Two prefixes with the same remainder mod k have a difference that is a multiple of k. Store the first index of each remainder, and check the distance is at least 2. Again, keep the earliest index, because a later one would only make the subarray shorter.

Subarray Sums Divisible by K (count them). Same remainder idea, but you count pairs, so the map holds counts and is seeded with {0: 1}.

Python
def find_max_length(nums): """Contiguous Array: longest subarray with equal 0s and 1s.""" first = {0: -1} # prefix 0 is seen "before" index 0 prefix = best = 0 for i, x in enumerate(nums): prefix += 1 if x == 1 else -1 if prefix in first: best = max(best, i - first[prefix]) else: first[prefix] = i # keep the EARLIEST index only return best def check_subarray_sum(nums, k): """Continuous Subarray Sum: length >= 2 and sum is a multiple of k.""" first = {0: -1} prefix = 0 for i, x in enumerate(nums): prefix = (prefix + x) % k if prefix in first: if i - first[prefix] >= 2: return True else: first[prefix] = i return False def subarrays_div_by_k(nums, k): """Subarray Sums Divisible by K: count them.""" count = [0] * k count[0] = 1 prefix = total = 0 for x in nums: prefix = (prefix + x) % k # Python % is never negative for k > 0 total += count[prefix] count[prefix] += 1 return total assert find_max_length([0, 1]) == 2assert find_max_length([0, 1, 0]) == 2assert find_max_length([0, 0, 1, 0, 0, 0, 1, 1]) == 6assert check_subarray_sum([23, 2, 4, 6, 7], 6) is Trueassert check_subarray_sum([23, 2, 6, 4, 7], 13) is Falseassert check_subarray_sum([5, 0, 0, 0], 3) is True # [0, 0] sums to 0, a multiple of 3assert check_subarray_sum([6], 6) is False # too shortassert subarrays_div_by_k([4, 5, 0, -2, -3, 1], 5) == 7assert subarrays_div_by_k([-1, 2, 9], 2) == 2print(-7 % 5, "in Python; JavaScript gives -2")print("all variant tests pass")
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Match each problem to what goes in the hash map.

Choose an item, then its match on the other side.

Prefix products: Product of Array Except Self

"Return an array where out[i] is the product of every element except nums[i], in O(n), without division." Division fails on zeros, and the interviewer bans it anyway. The answer for i is (product of everything left of i) times (product of everything right of i). Those are a prefix product and a suffix product.

You can store both in two arrays, but the follow-up is always "O(1) extra space, not counting the output". Do it in two passes: the first fills out[i] with the left product, and the second walks backwards with a single right variable and multiplies it in.

Python
def product_except_self(nums): n = len(nums) out = [1] * n left = 1 for i in range(n): # out[i] = product of everything LEFT of i out[i] = left left *= nums[i] right = 1 for i in range(n - 1, -1, -1): # multiply in everything RIGHT of i out[i] *= right right *= nums[i] return out assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0]assert product_except_self([0, 0, 2]) == [0, 0, 0]print(product_except_self([2, 3, 4, 5]))
Output
Press Run (⌘ Enter) to see what happens.

Note the order inside each loop: write out[i] before multiplying nums[i] into the running product. That is what "except self" means. The same "left pass, right pass" shape solves Trapping Rain Water (max to the left, max to the right) and Candy (constraints from each side). Find the Bottleneck uses this problem too, as an example of removing the inner loop.

2D prefix sums

A heat map, an image, a seating chart: "sum of the sub-rectangle from (r1, c1) to (r2, c2)" asked many times. Build P with one extra row and column, where P[r][c] is the sum of the rectangle from the top-left corner up to (but not including) row r and column c. A query is inclusion-exclusion: take the big rectangle, cut off the strip above and the strip to the left, then add back the corner you cut off twice.

Sum of rows 2..4, cols 1..3 (answer 8)
01234
030142
156321
212015
341017
410305

The target rectangle. A loop would add 9 cells. We want 4 lookups instead, whatever its size.

1/5

The same inclusion-exclusion builds the table: each cell is its own value plus the cell above plus the cell to the left, minus the diagonal cell that both of those include.

Python
class NumMatrix: def __init__(self, grid): rows, cols = len(grid), len(grid[0]) # P[r][c] = sum of the rectangle from (0, 0) to (r - 1, c - 1) self.P = [[0] * (cols + 1) for _ in range(rows + 1)] for r in range(rows): for c in range(cols): self.P[r + 1][c + 1] = (grid[r][c] + self.P[r][c + 1] + self.P[r + 1][c] - self.P[r][c]) def sum_region(self, r1, c1, r2, c2): P = self.P return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1] grid = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5],]m = NumMatrix(grid)assert m.sum_region(2, 1, 4, 3) == 8assert m.sum_region(1, 1, 2, 2) == 11assert m.sum_region(1, 2, 2, 4) == 12assert m.sum_region(0, 0, 4, 4) == sum(map(sum, grid)) import randomrandom.seed(2)for _ in range(200): r1, r2 = sorted(random.randrange(5) for _ in range(2)) c1, c2 = sorted(random.randrange(5) for _ in range(2)) brute = sum(grid[r][c] for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)) assert m.sum_region(r1, c1, r2, c2) == bruteprint("2D prefix sums agree with brute force")print(m.sum_region(2, 1, 4, 3))
Output
Press Run (⌘ Enter) to see what happens.

Build P with a list comprehension, never [[0] * (cols + 1)] * (rows + 1). That second form makes every row the same list object, so writing one cell writes the whole column. This exact bug shows up in real code review. Graphics people call this table a summed-area table or integral image, and it is how box blurs and some face detectors get constant-time rectangle sums.

Difference arrays: range updates in O(1)

Now flip the problem. Instead of many range queries on a fixed array, you get many range updates ("add v to every index from l to r") and only need the final array once. Updating each index is O(length of range) per update. A difference array makes each update O(1).

Store changes instead of values: diff[l] += v says "from here on, everything is v higher", and diff[r + 1] -= v says "from here on, stop adding it". One prefix-sum pass over diff rebuilds the real array. Difference and prefix sum are inverses, like a derivative and an integral.

Three range adds on 5 zeros, then one prefix pass
0
0
0
1
0
2
0
3
0
4
0
5
update = none yet

diff has n + 1 = 6 slots. The spare slot at the end absorbs r + 1 when r is the last index, so there is no bounds check.

1/5

Two classic problems are this exact pattern. Corporate Flight Bookings gives 1-based ranges of flights and seat counts, and asks for the total per flight. Car Pooling asks whether a car is ever over capacity, where each trip picks up passengers at from and drops them at to. Watch the boundary: passengers leave at to, so the trip covers from..to-1 and you subtract at to, not to + 1. Reading the boundary rule from the problem statement is the whole difficulty.

Python
def apply_range_adds(n, updates): """updates: (l, r, v) means add v to every index in l..r inclusive.""" diff = [0] * (n + 1) # one spare slot so r + 1 never overflows for l, r, v in updates: diff[l] += v diff[r + 1] -= v out, running = [], 0 for i in range(n): # one prefix pass rebuilds the array running += diff[i] out.append(running) return out def corp_flight_bookings(bookings, n): # flights are numbered 1..n, so shift to 0-based return apply_range_adds(n, [(f - 1, l - 1, seats) for f, l, seats in bookings]) def car_pooling(trips, capacity): last = max(to for _, _, to in trips) diff = [0] * (last + 1) for people, frm, to in trips: diff[frm] += people diff[to] -= people # they get out AT `to`, so no +1 here load = 0 for change in diff: load += change if load > capacity: return False return True assert apply_range_adds(5, [(1, 3, 2), (2, 4, 3), (0, 2, -2)]) == [-2, 0, 3, 5, 3]assert corp_flight_bookings([[1, 2, 10], [2, 3, 20], [2, 5, 25]], 5) == [10, 55, 45, 25, 25]assert car_pooling([[2, 1, 5], [3, 3, 7]], 4) is Falseassert car_pooling([[2, 1, 5], [3, 3, 7]], 5) is Trueassert car_pooling([[2, 1, 5], [3, 5, 7]], 3) is True # drop-off and pick-up at 5print(corp_flight_bookings([[1, 2, 10], [2, 3, 20], [2, 5, 25]], 5))
Output
Press Run (⌘ Enter) to see what happens.

When the positions are huge (timestamps in milliseconds, say) you cannot allocate an array that long. Store the +v and -v events in a dictionary or a list of (position, delta) pairs, sort the positions, and take the running total in that order. That is the sweep line from the Intervals lesson: a difference array over sorted event points. Meeting Rooms II, "maximum population year" and "busiest minute in the logs" are all this.

Put it in order4 steps

Put the steps of the difference-array method in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

When prefix sums break

Updates mixed with queries. A prefix array is a snapshot. Change one element and every prefix after it is stale, so a point update costs O(n). A difference array has the mirror problem: cheap updates, but reading a single value needs a prefix pass. When updates and queries interleave ("update account 7, then ask for the total of accounts 3..900, repeat a million times"), you need a Fenwick tree (binary indexed tree) or a segment tree, both O(log n) per operation. They are covered in Fenwick Trees, Segment Trees and Sorted Containers. In an interview, saying "if the array were mutable between queries I would switch to a Fenwick tree" is a strong signal even when you do not implement it.

Overflow. Python integers never overflow, so you will not see this in practice here. In Java, C++, C# and Go, a prefix sum of 10^5 values up to 10^9 reaches 10^14, far past a 32-bit int. Use a 64-bit type for the prefix array even when the inputs fit in 32 bits. In JavaScript, plain numbers are exact only up to 2^53 - 1 (about 9 × 10^15). Prefix products overflow much faster, which is one more reason problems that involve them usually ask for an answer modulo 10^9 + 7.

Floating point. Prefix sums of floats accumulate rounding error, and prefix[r + 1] - prefix[l] subtracts two large, nearly equal numbers, which loses precision. For money, store integer cents. For measurements, be aware the result can drift in the last digits.

Memory. A 2D prefix table doubles the memory of the grid. For a large image that matters, and for a sparse grid it is usually wasteful.

Quick check
You have 10^5 numbers. You will receive 10^5 operations, each either 'set index i to v' or 'sum of l..r', in any order. What fits best?
Need a nudge? A hint rules out a wrong answer.

How it shows up at work

You rarely write prefix[i + 1] = prefix[i] + a[i] by hand in production, but you use the idea constantly. SQL window functions (SUM(amount) OVER (ORDER BY day)) compute running totals in the database. Analytics systems store cumulative counters, and a monitoring query that asks for the increase over a time range is subtracting two points on a cumulative series. Rate limiters and quota systems keep per-bucket counts and sum ranges of buckets. Billing jobs that apply many date-range adjustments are difference arrays in disguise: record the start and end deltas, then sweep. Knowing the pattern lets you spot when a loop inside a loop in a report job is really one pass waiting to happen.

Practice

These are in Practice: Subarray Sum Equals K, Continuous Subarray Sum, Product of Array Except Self, Corporate Flight Bookings, Car Pooling and Maximum Population Year. For each one, say out loud what the running value is, what goes in the map or the diff array, and where the boundary is, before you write code.

Predict the outputPython

What does this print?

from collections import defaultdict
seen = defaultdict(int)
seen[0] = 1
prefix = count = 0
for x in [0, 0]:
  prefix += x
  count += seen[prefix - 0]
  seen[prefix] += 1
print(count)
Need a nudge? Hints walk you through it.
Key terms
prefix sum
An array where entry i holds the sum of the first i elements, so any range sum is one subtraction.
prefix map
A hash map from running prefix value to its count or first index, used to find subarrays with a target sum in one pass.
prefix product
Running products from the left (or right), used for Product of Array Except Self without division.
inclusion-exclusion
Adding and subtracting overlapping regions so each cell is counted exactly once, as in 2D range sums.
summed-area table
A 2D prefix sum table. Any rectangle sum takes four lookups.
difference array
Stores changes between neighbours, so a range update is two writes and one prefix pass rebuilds the values.
Fenwick tree
A structure that supports point updates and prefix sums in O(log n) each, for when updates and queries interleave.