Lessons 21–25 · About 60 min per lesson

Fenwick trees and dynamic range queries

Answer range sums efficiently even as the data changes.

Lesson breakdown

  1. Lesson 21

    Identify the cost of frequent point updates to static prefix sums.

  2. Lesson 22

    Use one-based indexes and lowbit to describe each node’s range.

  3. Lesson 23

    Implement point updates and visit each affected node.

  4. Lesson 24

    Obtain inclusive range sums from prefixes and check the empty prefix.

  5. Lesson 25

    Compare each operation against a linear reference and analyse both costs.

Worked example

For one-based [2,1,4,3], query [2,4], add 2 to element 3 and query again.

How to solve it

The result changes from 1+4+3=8 to 1+6+3=10. Both queries use prefix(4) − prefix(1).

Assignment

Implement point additions and inclusive range sums, comparing with a reference on updates that may include negative values.

Check your result

The example gives 8 and 10. Subtract 3 from element 1, then [1,1] → -1 and [2,4] stays 10.