Fenwick trees: prefix sums that update in O(log n)

Video lessonComing soon

1 When the book gets a correction

The lesson on prefix sums gave the shop a running-total column. With it, any range of days became one subtraction. That works while the book never changes.

Now the owner finds mistakes in old entries and corrects them, in between questions. Here is the book for eight days. This time we number the days from 1, and the code section shows why.

2132-131435264718
Profit on days 1 to 8, in thousands of rupees

Day 3 should have been 1, not −1. After the fix, every running total from day 3 on goes up by 2. So one correction can rewrite almost the whole column. Without the column, a correction is one write, but each question adds up the days again. Either way, one of the two jobs costs O(n):

The book keepsCorrect one daySum of days 1 to i
Only the daysO(1)O(n)
Running totalsO(n)O(1)
A Fenwick treeO(log n)O(log n)

With 10⁵ days, 10⁵ corrections and 10⁵ questions, both of the first two take around 10¹⁰ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets Time Limit Exceeded (TLE).

A Fenwick tree does each job in about 17 steps. It is also called a binary indexed tree, or BIT.

2 Blocks sized by the lowest 1 bit

Any count of days splits into powers of two, one for each 1 bit in its binary. 7 is 111 in binary, so 7 = 4 + 2 + 1. Days 1 to 7 are then three blocks: days 1 to 4, days 5 to 6, and day 7.

With each block's sum ready, a prefix sum adds one block per 1 bit. A number up to 10⁵ has 17 bits, so that is at most 17 blocks.

A Fenwick tree keeps these blocks in an array tree. Box i holds the sum of one block:

  • It ends at day i.
  • Its length is the lowest 1 bit of i. The lesson on bit operators showed that i & -i keeps only that bit.

Day 6 is 110 in binary. Its lowest 1 bit is 2, so tree[6] holds days 5 and 6. Day 8 is 1000, so tree[8] holds all eight days. Every odd day has 1 as its lowest bit, so its box holds that day alone.

The picture shows the days on top. Under them are the blocks, one row per length: 1, 2, 4 and 8. Each block's sum sits in its last cell, under the day where it ends.

2132-1314352647182-13455515
Days 1 to 8, and the block each box holds
ibinaryi & -iblocktree[i]
100011day 12
200102days 1 to 25
300111day 3−1
401004days 1 to 45
501011day 53
601102days 5 to 65
701111day 74
810008days 1 to 815

The rest of the lesson reads off this picture. A prefix sum walks left across it, and an update walks down one column.

3 A prefix sum walks left

To add up days 1 to 7, we start at box 7. Its block is day 7 alone. The days still missing are 1 to 6, and they end at day 6, so the next box is 6. Box 6 holds days 5 and 6. The days still missing end at day 4, and box 4 holds all of them.

prefix(7) collects three blocks
2132-1314352647182-13455515i
i = 7: add box 7, total 4. Next i = 6

Each jump goes from i to i - (i & -i), the day just before i's block starts. So the blocks meet end to end, with no gap and no overlap. In binary, each jump removes the lowest 1 bit:

ibinaryi & -iblocktree[i]total
701111day 744
601102days 5 to 659
401004days 1 to 4514
00000stop14

The binary column loses one 1 bit per row. So the walk takes one step per 1 bit of i, at most 17 steps for 10⁵ days.

A sum of days l to r is two of these walks, as in the prefix-sums lesson. Days 3 to 7 made prefix(7) − prefix(2) = 14 − 5 = 9.

sum of days l..r = prefix(r) − prefix(l − 1)

4 An update walks down one column

The owner corrects day 3 from −1 to 1. The change from the old value to the new one is the delta, here +2. Every box whose block covers day 3 must grow by 2, and no other box may change. In the picture, those blocks sit in day 3's column: boxes 3, 4 and 8.

This walk jumps the other way, from i to i + (i & -i):

update(3, +2) reaches every block over day 3
2132131435264718213455515i
i = 3: box 3 goes from −1 to 1. Next i = 4
ibinaryi & -iblocktree[i] beforeafter
300111day 3−11
401004days 1 to 457
810008days 1 to 81517
1610000past day 8: stop

The jump lands on exactly the right boxes, for two reasons:

  • The next box covers day i. Adding the lowest 1 bit carries into a higher bit. So the next box's lowest 1 bit is at least twice as big, and its block reaches back over all of i's block. Box 4's block, days 1 to 4, covers box 3's.
  • The boxes skipped stop short of day i. Box 5 holds day 5, box 6 holds days 5 to 6, and box 7 holds day 7. None of them reaches back to day 3, so the walk can skip from 4 straight to 8.

The lowest 1 bit at least doubles at each jump, so this walk also takes at most about 17 steps for 10⁵ days. After it, prefix(7) is 16, two more than before.

5 The code, and why it counts from 1

The class keeps tree with n + 1 places and leaves box 0 unused. It builds itself by adding each day as an update. The values in nums start at index 0, so nums[i] goes into box i + 1.

C++

Keep sums in long long. tree and delta are 64-bit, so a sum past 2 × 10⁹ does not wrap around.

Keep sums in long. tree and delta are 64-bit, so a sum past 2 × 10⁹ does not wrap around.

Nothing to watch. Python's integers grow as needed, and i & -i works on them as on any integer.

Sums are safe up to about 9 × 10¹⁵. Numbers stay exact that far. i & -i works on 32 bits, which is plenty for an index.

int is 64 bits on today's machines, so sums of 10¹⁴ fit. The constructor is a plain function, newFenwick.

-i does not compile on usize. i.wrapping_neg() gives the same bits as −i, so i & i.wrapping_neg() is the lowest 1 bit. Sums are i64.

Keep sums in long. tree and delta are 64-bit, so a sum past 2 × 10⁹ does not wrap around.

Box 0 stays out because 0 has no 1 bit, so 0 & -0 is 0. An update at i = 0 would add 0 to i again and again, and the loop would never end. Counting from 1 avoids that.

Building with n updates costs O(n log n). A faster build copies the days into tree first. Then, from left to right, each box adds itself into the next box that covers it:

tree[1..n] = nums
for i from 1 to n
    parent = i + (i & -i)
    if parent <= n
        tree[parent] += tree[i]

Each box is complete when the loop reaches it, because every smaller box under it has already added itself in. This build is O(n).

6 Cost

  • Prefix sum: O(log n). The walk takes one step per 1 bit of i.
  • Update: O(log n). The lowest 1 bit at least doubles at each step.
  • Range sum: O(log n). It is two prefix sums.
  • Build: O(n log n) with n updates, or O(n) with the faster build.
  • Memory: O(n). One array of n + 1 sums, the same as a prefix array.

With 10⁵ days, 10⁵ corrections and 10⁵ questions, that is a few million steps in all, well inside the time limit.

7 Mistakes and edge cases

  • Indexes from 0. update(0, 5) never ends. 0 & -0 is 0, so i stays 0, and the program gets TLE. Problems usually number from 0, so add 1 on the way in: index j lives in box j + 1.
  • prefix(l) instead of prefix(l − 1). Days 3 to 7 then come out as 14 − 4 = 10 instead of 9. The subtraction takes day 3 away too.
  • The new value instead of the delta. To set day 3 to 1, update(3, 1) adds 1 to −1, so day 3 counts as 0. Then prefix(7) is 15 instead of 16. The tree holds block sums, so it cannot see a day's old value. Keep the days in their own array and pass new − old.
  • Overflow. 10⁵ days of 10⁹ each add up to 10¹⁴, far past the 32-bit limit of about 2 × 10⁹. Keep tree and the delta 64-bit, as the notes under the code say.

8 When to use a Fenwick tree

The sign is single values that change between questions about prefix or range sums. Range Sum Query - Mutable has exactly this shape, with indexes from 0.

The same tree can also count. When we add 1 to box v for each value v we see, prefix(v) counts the values seen that are at most v. Count of Smaller Numbers After Self asks questions of that kind. Its values run from −10⁹ to 10⁹, and a box for each would not fit. The next lesson, on coordinate compression, first shrinks them to ranks 1 to n.

The jobs can also swap round. Some problems add v to every day from l to r, then ask for one day's value. A difference array handles this, as in its own lesson. It marks +v at l and −v at r + 1, and a day's value is the running sum of the marks up to it. Kept in a Fenwick tree, each mark is one update, and a day's value is one prefix sum. Both stay O(log n), in any order.

A Fenwick tree needs a range to be one prefix minus another. A minimum or a maximum cannot be taken away like that. With changing values, those need the segment tree, a later lesson.

When values change between sum questions, do not rebuild the prefix array after each change. Ask whether a Fenwick tree can keep the prefix sums instead.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.