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

Lessons

  1. 1

    Prefix sums

    One pass of preparation answers every range-sum question in O(1): the most useful trick in contests.

  2. 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. 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

Module quiz

1. a = {1, 2, 3, 4}. What is pre with pre[0] = 0?
2. How do you add 7 to a[l..r] in a difference array?
3. The pair-sum two-pointer scan runs on a sorted array. What is its cost?
4. Why does the grow-and-shrink window need positive numbers?
5. 100,000 guests each stay from minute a to minute b. How do you find the busiest minute fast?
6. The array has negative numbers and you must count subarrays with sum k. What works?

‹ Contest basicsSearch, greedy and DP ›