Lessons 21–25 · About 60 min per lesson

Prefix totals and batch queries

Precompute totals to turn repeated interval scans into two lookups.

Lesson breakdown

  1. Lesson 21

    Build n+1 prefix sums starting at zero.

  2. Lesson 22

    Answer zero-indexed inclusive intervals with p[r+1] - p[l].

  3. Lesson 23

    Build a prefix count for one category.

  4. Lesson 24

    Use binary search on timestamps to find the queried index range.

  5. Lesson 25

    Compare with a direct scan and check first, last and empty ranges.

Worked example

For [3,1,4,2], sum inclusive indexes [1,3].

How to solve it

Prefix sums are [0,3,4,8,10]. The result is p[4] − p[1] = 10 − 3 = 7.

Assignment

Preprocess timestamped values and sum them in inclusive time ranges, including all records with repeated timestamps.

Check your result

For (2,3), (4,1), (4,4), [4,4] → 5 and [3,3] → 0.