Prefix sums and difference arrays
Precompute once, answer any range query in O(1) — the leading-zero convention that removes every off-by-one, the prefix-count map that solves subarray-sum problems a sliding window cannot touch, the difference array that makes range updates constant time, and the two dimensions where the same idea becomes inclusion–exclusion.
What you'll be able to do
- Build a prefix-sum array with the P[0] = 0 convention and derive any range sum from it
- Explain why a sliding window fails on arrays containing negatives, and what replaces it
- Solve "count subarrays summing to k" with a prefix-count map, including the seed that makes it correct
- Apply a difference array to answer m range updates in O(n + m) instead of O(nm)
- Say when prefix sums are the wrong structure and a Fenwick tree is required
Before this: hash-maps, sliding-window
The rest of this lesson is in the app
Precompute once, answer any range query in O(1) — the leading-zero convention that removes every off-by-one, the prefix-count map that solves subarray-sum problems a sliding window cannot touch, the difference array that makes range updates constant time, and the two dimensions where the same idea becomes inclusion–exclusion. This walkthrough runs about 24 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.