mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-17 15:36:26 +00:00
72 lines
1.6 KiB
Markdown
72 lines
1.6 KiB
Markdown
## Prefix Sum
|
||
|
||
Precompute cumulative totals once → any range sum in **O(1)**.
|
||
|
||
---
|
||
|
||
## Recognition
|
||
|
||
- Many range-sum queries over a static array
|
||
- "Count subarrays with sum k" (negatives allowed — window won't work)
|
||
- "Product/sum of everything except me" → prefix from both directions
|
||
|
||
---
|
||
|
||
## Template — range query (LC 303)
|
||
|
||
```js
|
||
// prefix[i] = sum of nums[0..i-1], prefix[0] = 0
|
||
const prefix = [0];
|
||
for (const x of nums) prefix.push(prefix[prefix.length - 1] + x);
|
||
|
||
// sum of nums[l..r] inclusive:
|
||
const rangeSum = (l, r) => prefix[r + 1] - prefix[l];
|
||
```
|
||
|
||
The leading 0 removes every edge case at `l = 0`.
|
||
|
||
---
|
||
|
||
## Template — prefix + hashmap (LC 560)
|
||
|
||
```js
|
||
function subarraySum(nums, k) {
|
||
const count = new Map([[0, 1]]); // empty prefix
|
||
let sum = 0;
|
||
let total = 0;
|
||
for (const x of nums) {
|
||
sum += x;
|
||
total += count.get(sum - k) ?? 0; // earlier prefix to cut off
|
||
count.set(sum, (count.get(sum) ?? 0) + 1);
|
||
}
|
||
return total;
|
||
}
|
||
```
|
||
|
||
sum(l..r) = prefix[r] − prefix[l−1] — so look up `sum - k`.
|
||
|
||
---
|
||
|
||
## Pitfalls
|
||
|
||
- Forgetting the seed `(0, 1)` misses subarrays starting at index 0
|
||
- Count **before** inserting the current prefix (a subarray has length ≥ 1)
|
||
- Sliding window fails here when values can be negative
|
||
|
||
---
|
||
|
||
## Recall
|
||
|
||
- Why does LC 560 need a hashmap instead of a window?
|
||
- LC 238 Product Except Self: how do prefix and suffix passes combine?
|
||
- LC 525 Contiguous Array: what do you turn 0s into, and why?
|
||
|
||
---
|
||
|
||
## Drill
|
||
|
||
- 303 Range Sum Query · 1480 Running Sum
|
||
- 238 Product of Array Except Self
|
||
- 560 Subarray Sum Equals K
|
||
- 525 Contiguous Array · 974 Subarray Sums Divisible by K
|