AlgoTales · Roadmap

Point update

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

In a Fenwick tree (also called a BIT), a point update changes one value and then touches just a handful of helper cells that hold sums over it. It keeps range totals correct while the data changes, with only a few steps per change.

Practical use cases

  • Web app: Live votes on a reality show page. Each vote adds one to a contestant count and the page shows totals for rankings instantly. A Fenwick tree updates the few cells covering that contestant, so thousands of votes per second keep totals fresh without recalculating everything. Viewers see rankings move almost live, and the server is not busy recomputing totals for every contestant on each vote.
  • Web app: Live leaderboard in a game or quiz. When a player scores, the scoreboard must reflect it and still tell any player how many are ahead of them. One point update touches around 20 cells even with a million players. This keeps quiz nights smooth, with rank lookups and score updates both finishing in a few dozen steps.
  • System: Frequency counters and inversion counting. Interview problems and analytics jobs that count how often values appear, or count out-of-order pairs, use quick point updates to keep running counts correct as items are processed. Without such quick updates, counting would be too slow to finish on lists with millions of values.

The story: The Switchboard in Mrs. Sharma's Office

Mrs. Sharma's school has 8 classrooms in a row, and the principal loves one question: "How many students are in rooms 1 to 5 right now?" Last year Zoya the clerk kept a running-total sheet, a prefix sum. It answered every question instantly, until the admission season. Each new student changed one room, and suddenly every running total after that room was wrong. Zoya spent whole afternoons rewriting the sheet.

Grandpa Bhaskar, the old electrician, was watching the office switchboard. "Beta, look at this board. Every room number is a pattern of little switches, worth 8, 4, 2 and 1. Room 6 is the 4-switch and the 2-switch ON. Now, the lowest ON switch tells you how big a territory your helper should look after." Room 4 has only the 4-switch on, so its helper keeps the total of 4 rooms (1 to 4). Room 6 has 2 as its lowest, so its helper keeps rooms 5 and 6. Room 7 has 1 as its lowest, so its helper tracks only room 7.

Now when a new student joins room 3, who must be told? Room 3's helper first. Then take the lowest ON switch of 3 (that is 1) and add it: you land on 4, whose territory also contains room 3. Tell box 4. Its lowest switch is 4, so add it and land on 8. Tell box 8. Add again and you fall off the board. Only three helpers changed instead of six running totals. This clever board of helpers is called a Fenwick tree, or Binary Indexed Tree.

How to spot this problem, and where you need it

Numbers change one at a time while people keep asking for running totals, so recomputing prefix totals after every change is too slow.

Signs you need it

  • A plain prefix-sum list worked, until the underlying values started changing.
  • Each change forces you to rebuild or loop over a long list of totals.
  • The system has many updates and many sum or rank queries mixed together.
  • The problem says "update value at index i" and "sum up to index j".

Where to use it in a project

  • Voting, like or view counters that also show ranks or totals.
  • Leaderboards and live statistics for games, quizzes and exams.

The solution

Store totals in a Fenwick tree where each cell covers a block of positions whose size is a power of two. To change position i, add the change to cell i, then jump to the next cell that also covers i (add the lowest set bit of the index) and repeat until past the end. Only about as many cells as there are bits get touched.

Payoff: Before: rebuilding a million running totals per vote. After: about 20 cell updates, so counts stay live.

Explain it like I am 8

Think of a phone tree for a school notice. When something changes in room 3, you call the helper for room 3. That helper then calls exactly one bigger helper, who calls one bigger helper, until nobody is left to call. The light switches on the office board tell each person who to call next: add the value of your lowest ON switch to your own number.

How it works, step by step

  1. Number the shelves from 1. Keep a helper box for each shelf, starting at 0.
  2. Each box has a territory. The lowest ON switch of its number tells how many shelves it covers (itself and the ones just before it).
  3. To add something to shelf i, add it to box i.
  4. Climb to the next box: i = i + (value of the lowest ON switch of i). In code that is i += i & -i.
  5. Keep climbing and adding until the number goes past the last shelf. Only about as many boxes as switches are touched.

The code in four languages

PHP

<?php
// The lowest ON switch of i, and nothing else: 6 (0110) -> 2, 4 (0100) -> 4
function lowbit(int $i): int {
    return $i & -$i;
}

// Add $delta to shelf $i (shelves are numbered from 1)
function fenwickAdd(array &$t, int $i, int $delta): void {
    $n = count($t) - 1;                 // t[0] is unused
    while ($i <= $n) {
        $t[$i] += $delta;               // tell this helper box
        $i += lowbit($i);               // climb to the next box that covers us
    }
}

$a = [5, 3, 7, 2, 6, 4, 1, 8];
$t = array_fill(0, count($a) + 1, 0);
foreach ($a as $k => $v) {
    fenwickAdd($t, $k + 1, $v);         // build by adding each number once
}
echo implode(',', array_slice($t, 1)) . PHP_EOL;   // 5,8,7,17,6,10,1,36

fenwickAdd($t, 3, 3);                   // room 3 gets 3 more students
echo implode(',', array_slice($t, 1)) . PHP_EOL;   // 5,8,10,20,6,10,1,39  (boxes 3, 4, 8 changed)

JavaScript

// The lowest ON switch of i, and nothing else: 6 (0110) -> 2, 4 (0100) -> 4
function lowbit(i) {
  return i & -i;
}

// Add delta to shelf i (shelves are numbered from 1)
function fenwickAdd(t, i, delta) {
  const n = t.length - 1;               // t[0] is unused
  while (i <= n) {
    t[i] += delta;                      // tell this helper box
    i += lowbit(i);                     // climb to the next box that covers us
  }
}

const a = [5, 3, 7, 2, 6, 4, 1, 8];
const t = new Array(a.length + 1).fill(0);
a.forEach((v, k) => fenwickAdd(t, k + 1, v));       // build by adding each number once
console.log(t.slice(1).join(','));                  // 5,8,7,17,6,10,1,36

fenwickAdd(t, 3, 3);                                // room 3 gets 3 more students
console.log(t.slice(1).join(','));                  // 5,8,10,20,6,10,1,39  (boxes 3, 4, 8 changed)

Java

import java.util.*;

public class Main {
    // The lowest ON switch of i, and nothing else: 6 (0110) -> 2, 4 (0100) -> 4
    static int lowbit(int i) {
        return i & -i;
    }

    // Add delta to shelf i (shelves are numbered from 1)
    static void fenwickAdd(int[] t, int i, int delta) {
        int n = t.length - 1;               // t[0] is unused
        while (i <= n) {
            t[i] += delta;                  // tell this helper box
            i += lowbit(i);                 // climb to the next box that covers us
        }
    }

    public static void main(String[] args) {
        int[] a = {5, 3, 7, 2, 6, 4, 1, 8};
        int[] t = new int[a.length + 1];
        for (int k = 0; k < a.length; k++) {
            fenwickAdd(t, k + 1, a[k]);     // build by adding each number once
        }
        System.out.println(Arrays.toString(Arrays.copyOfRange(t, 1, t.length)));   // [5, 8, 7, 17, 6, 10, 1, 36]

        fenwickAdd(t, 3, 3);                // room 3 gets 3 more students
        System.out.println(Arrays.toString(Arrays.copyOfRange(t, 1, t.length)));   // [5, 8, 10, 20, 6, 10, 1, 39]  (boxes 3, 4, 8 changed)
    }
}

Go

package main

import "fmt"

// lowbit returns the lowest ON switch of i, and nothing else: 6 (0110) -> 2, 4 (0100) -> 4
func lowbit(i int) int {
	return i & -i
}

// fenwickAdd adds delta to shelf i (shelves are numbered from 1).
func fenwickAdd(t []int, i, delta int) {
	n := len(t) - 1 // t[0] is unused
	for i <= n {
		t[i] += delta  // tell this helper box
		i += lowbit(i) // climb to the next box that covers us
	}
}

func main() {
	a := []int{5, 3, 7, 2, 6, 4, 1, 8}
	t := make([]int, len(a)+1)
	for k, v := range a {
		fenwickAdd(t, k+1, v) // build by adding each number once
	}
	fmt.Println(t[1:]) // [5 8 7 17 6 10 1 36]

	fenwickAdd(t, 3, 3) // room 3 gets 3 more students
	fmt.Println(t[1:])  // [5 8 10 20 6 10 1 39]  (boxes 3, 4, 8 changed)
}

Time: O(log n) per update · Extra space: O(n). Each hop jumps to a bigger box, and there are only as many hops as there are switches in the biggest room number.

Watch out for

  • Starting the shelves at 0. The trick needs numbers from 1, because the lowest ON switch of 0 does not exist and the loop never moves.
  • Updating only box i and forgetting to climb, which leaves the bigger boxes stale.
  • Using the new value instead of the change. Update boxes by adding the difference (new minus old).

Quick check

  1. Room 3 changes. After box 3, which box is next?
    • Box 2
    • Box 4
    • Box 6
  2. What does the lowest ON switch of a box number tell you?
    • Whether the box is full
    • Which room is the biggest
    • How many shelves that box covers
  3. When does the climbing stop?
    • After exactly 3 hops
    • When the number goes past the last shelf
    • When the box is 0