Prefix Sums in Coding Interviews: A Practical Guide Prefix sums turn "sum of a range" questions from O(n) per query into O(1). They also power a family of hash-map tricks that interviewers love. Here is how to recognize and explain them.
1. The basic idea Build pre[0] = 0 and pre[i+1] = pre[i] + nums[i]. The sum of nums[l..r] is pre[r+1] - pre[l]. One pass to build, constant time per query (Range Sum Query - Immutable).
2. Prefix sum plus hash map To count subarrays that sum to k, walk the array keeping a running sum and a map from "prefix sum seen" to "how many times". At each step add count[sum - k] to the answer. This is O(n) and handles negative numbers, which a sliding window cannot. The same template solves: longest subarray with sum k (store the first index instead of a count), contiguous array with equal 0s and 1s (map 0 to -1), and subarray sums divisible by k (key on sum % k).
3. 2D prefix sums For a matrix, P[i+1][j+1] = M[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]. Any rectangle sum is four lookups. Mention inclusion-exclusion by name when you explain it.
4. Difference arrays (the reverse trick) When many updates add a value to a range, record diff[l] += v and diff[r+1] -= v, then take a prefix sum at the end. Car pooling and corporate flight bookings are classic examples.
5. Pitfalls to call out • Off-by-one errors: use a leading zero so pre has length n+1. • Seed the hash map with {0: 1} (or {0: -1} for index versions), or you miss subarrays starting at index 0. • In languages with fixed-width integers, prefix sums can overflow; use 64-bit. • Negative modulo results in Java and C++: normalize with ((sum % k) + k) % k.
How to present it Say the pattern out loud ("range sum, so prefix sums"), write the one-line recurrence, and state the seed value before coding. Practicing that explanation under time pressure is the hard part; I rehearse with AI interview copilot sessions from Linkjob AI. Disclosure: I work on Linkjob AI.