#307

Range Sum Query - Mutable

Medium Fenwick tree (BIT)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Support two operations on an array: update one element, and return the sum of a range. Both must be fast.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: change single values and ask range sums, both fast.

Why this works: a Fenwick tree updates and sums prefixes in O(log n); a range sum is the difference of two prefix sums.

Example: [1, 3, 5]

sum(0..2) = 9update index 1 to 2 → add -1sum(0..2) = 8

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Passing the new value to add() instead of the difference from the old value.

Solve on LeetCode ↗
Complexity
  • Time: O(log n) per update and query; O(n log n) to build.
  • Space: O(n).
Topic: Segment Tree, Fenwick & Sparse Table
🎬 Episodes 98–100: video coming soon