Prefix Sum
Think of a car’s trip meter. To know how far you drove between two towns, you subtract the two readings. A prefix sum writes down the reading after every number, so the total of any stretch is one subtraction.
2 · Watch
Prefix Sum in 60 seconds
3 · Now you drive
Subarray Sum Equals K
4 · Your turn
Start from this
// How many times each running total has shown up. The empty prefix is 0.
const seen = new Map<number, number>([[0, 1]]);
let prefix = 0;
let answer = 0;
for (const x of nums) {
prefix += x;
// A run ending here is good when an earlier total was prefix - k.
answer += seen.get(prefix - k) ?? 0;
// Store the total only after the lookup, so a run is never empty.
seen.set(prefix, (seen.get(prefix) ?? 0) + 1);
}
return answer;Easy ways to go wrong
- Forgetting to seed the map with 0, which misses every run that starts at index 0.
- Storing the total before the lookup, which counts an empty run when k is 0.
- Using a sliding window when the numbers can be negative. The window sum no longer grows as it widens.
- Taking a remainder of a negative total in JavaScript, which stays negative. Add k and take it again.
- Easy01
Range Sum Query - Immutable
Store the running totals once. Each question is then one subtraction.
Lots of range questions on fixed data: pay O(n) once, then answer each in O(1).
- Time
- O(1) per query
- Space
- O(n)
O(1) per query time · O(n) spaceclass NumArray { // sums[i] is the total of the first i numbers, so sums[0] is 0. private sums: number[] = [0]; constructor(nums: number[]) { for (const x of nums) this.sums.push(this.sums[this.sums.length - 1] + x); } sumRange(left: number, right: number): number { // Everything up to right, minus everything before left. return this.sums[right + 1] - this.sums[left]; } } - Medium02
Subarray Sum Equals K
The one you just watched. Write it from memory.
Negative numbers break a sliding window, but a total minus an earlier total still gives any run.
- Time
- O(n)
- Space
- O(n)
Also works with Arrays & Hashing.
O(n) time · O(n) spacefunction subarraySum(nums: number[], k: number): number { const seen = new Map<number, number>([[0, 1]]); // prefix sum → times seen let prefix = 0; let count = 0; for (const x of nums) { prefix += x; // A subarray ending here sums to k once for each earlier prefix of prefix - k. count += seen.get(prefix - k) ?? 0; seen.set(prefix, (seen.get(prefix) ?? 0) + 1); } return count; } - Medium03
Contiguous Array
Count each 0 as -1, so a balanced run sums to 0. Keep the first index of each total.
Equal counts become a zero sum. The longest run starts just after a total first appeared.
- Time
- O(n)
- Space
- O(n)
O(n) time · O(n) spacefunction findMaxLength(nums: number[]): number { // The first index where each running total showed up. Total 0 comes "before index 0". const first = new Map<number, number>([[0, -1]]); let prefix = 0; let best = 0; for (let i = 0; i < nums.length; i++) { prefix += nums[i] === 1 ? 1 : -1; // count each 0 as -1 const at = first.get(prefix); if (at === undefined) first.set(prefix, i); // Same total as before: the run in between has as many 0s as 1s. else best = Math.max(best, i - at); } return best; } - Medium04
Continuous Subarray Sum
Store each total’s remainder mod k with the first index it showed up at.
Two totals with the same remainder mod k differ by a multiple of k.
- Time
- O(n)
- Space
- O(min(n, k))
O(n) time · O(min(n, k)) spacefunction checkSubarraySum(nums: number[], k: number): boolean { // The first index where each remainder mod k showed up. const first = new Map<number, number>([[0, -1]]); let rem = 0; for (let i = 0; i < nums.length; i++) { rem = (rem + nums[i]) % k; const at = first.get(rem); if (at === undefined) first.set(rem, i); // Same remainder: the run in between sums to a multiple of k. else if (i - at >= 2) return true; } return false; } - Medium05
Subarray Sums Divisible by K
Count remainders instead of totals, and turn negative remainders positive.
The same remainder at two cuts means the run between them divides by k.
- Time
- O(n)
- Space
- O(k)
O(n) time · O(k) spacefunction subarraysDivByK(nums: number[], k: number): number { // How many running totals had each remainder. The empty prefix has remainder 0. const count: number[] = new Array(k).fill(0); count[0] = 1; let rem = 0; let answer = 0; for (const x of nums) { // % keeps the sign in JavaScript, so add k to land in 0..k-1. rem = (((rem + x) % k) + k) % k; answer += count[rem]; count[rem]++; } return answer; }