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.
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.
What does this print?
p = [0] for x in [2, -1, 3, 4]: p.append(p[-1] + x) print(p[4] - p[1])
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).
Seed the map with {0: 1}. That is the empty prefix, and it lets a subarray that starts at index 0 be counted.
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]withk = 3returns 0. - Count first, then record. Look up
prefix - kbefore adding the current prefix to the map. If you record first andk = 0, every position matches itself and you count empty subarrays.
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}.
Press Run (⌘ Enter) to see what happens.Match each problem to what goes in the hash map.
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.
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.
The target rectangle. A loop would add 9 cells. We want 4 lookups instead, whatever its size.
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.
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.
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.
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.
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 the steps of the difference-array method in order.
- Tap the steps below in the right order.
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.
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.
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)
- 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.