Array techniques
Prefix sums for range queries, difference arrays for range updates, and two pointers for pairs and windows, all in O(n).
About 6 hours of study
Learning objectives
- Answer range sums in O(1)
- Apply range updates with a difference array
- Use two pointers and sliding windows
Lessons
- 1
Prefix sums
One pass of preparation answers every range-sum question in O(1): the most useful trick in contests.
- 2
Difference arrays
Add a value to a whole range in O(1) by marking only its two ends, then rebuild the array with one prefix-sum pass.
- 3
Two pointers and sliding windows
Two indexes that only move forward turn many O(n²) searches into O(n): pair sums in a sorted array, and windows.
Module practice
- CP: Running totalsEasy
- CP: Range sum queriesMedium
- CP: Subarrays that add up to kHard
- CP: Many range additionsEasy
- CP: The busiest momentMedium
- CP: Paint the gridHard
- CP: Is there a pair?Easy
- CP: The best windowMedium
- CP: The shortest segment with enough sumHard