Algorithms

Fenwick tree

Mira was in fifth place. She earned three more points and tied Max. How can we tell her new rank when scores keep changing? A Fenwick tree stores totals for groups of scores, so we can quickly count how many players scored higher than Mira.

Leaderboard
RankPlayerScore
1Ada8
2Max6
3Lina5
4Oleg4
5Mira3
6Lev2
Mira · 3 → 6Players grouped by score
Players grouped by score
Score12345678
Count01111101

Score 3 → Mira → 1 player

Tree of sums

Each node shows its index and sum. Arrows point to parents.

Build the tree. Start each node with the number of players with its score.

Video walkthrough

Count the players ahead

Take the Score column from the leaderboard and group players by score. Lina has 5 points and Max has 6. They each start alone in their group, so the counts below 5 and 6 are both 1. When Mira moves to 6, that count becomes 2. The highlights connect groups to the names in the leaderboard.

A player’s rank is one plus the number of people with a strictly higher score. Mira starts with 3 points. Two players scored 3 or lower and four scored higher, putting her in fifth place.

Players with the same score share a rank. When two players tie for second, the player after them takes fourth place.

What each tree cell stores

Cell T[i] stores the total for a block of scores ending at i. Its length lowbit(i) is the value of the lowest set bit in the index. For example, 6 is 110 in binary. Its lowest set bit is worth 2, so T[6] counts players with scores of 5 and 6. T[4] covers scores from 1 through 4.

The diagram draws each cell T[i] as a node with index i. Draw an arrow from i to i + lowbit(i) when that index exists. The parent stores the smallest larger block that contains the current one. For example, the arrow from 6 points to 8 because 6 + 2 = 8. Root 8 has no parent.

Build the tree from the score counts

Start node i with the number of players who scored exactly i. Nodes 5 and 6 each start at 1, and node 8 starts at 1 for Ada.

Visit nodes in increasing index order. Each node adds its accumulated sum to its parent. By the time we visit a node, its descendants have already contributed because their indexes are smaller. Node 5 adds 1 to the 1 in node 6. Now T[6] = 2, and node 6 passes the full 2 on to node 8.

In the finished tree, T[4] = 3 for scores 1–4, T[6] = 2 for scores 5–6, and T[8] = 6 for all scores. The opening steps of the demo show those additions along the arrows.

Update Mira’s rank

Mira’s score changes from 3 to 6. First subtract one from the frequency for 3 and from the three totals T[3], T[4], and T[8]. Then add one to the frequency for 6 and to T[6] and T[8]. At each update, add lowbit(i) to reach the next index. This visits every stored block containing the changed score.

To query the total for scores 1 through i, read T[i] and subtract the block length from i. The new index is the end of the block immediately to the left. For score 6, read node 6, then node 4, and stop at zero.

Now T[6] = 3 and T[4] = 2. Five players scored at most 6. Six players are on the board, so one is ahead. Mira and Max share second place. The demo shows individual tree writes during the move. The leaderboard shows the new ranks once the move is complete.

What an update costs

Let P be the number of players and M the maximum score. The tree uses O(M) memory and the current scores use O(P). Building takes O(P + M). Count the players in one pass, then pass each node’s sum to its parent at most once. A rank query and a score change each take O(log(M + 1)).

During construction, a highlight shows a sum moving along one edge. During queries and updates, each step reads or writes one tree cell. The demo also keeps playback frames and sorts six rows for display. Finding one player’s rank uses only the tree and the total number of players.

JavaScript implementation

Players are indexed from zero and scores from one. Assume maxScore and scores are integers from 1 to 2³¹ − 1, scores are at most maxScore, and player indexes are valid. The limit comes from JavaScript’s 32-bit bitwise operators. The demo uses scores from 1 to 8.

function createLeaderboard(scores, maxScore) {
    const current = [...scores];
    const tree = Array(maxScore + 1).fill(0);
    const lowbit = i => i & -i;

    function add(score, delta) {
        for (let i = score; i <= maxScore; i += lowbit(i)) {
            tree[i] += delta;
        }
    }

    function prefix(score) {
        let count = 0;
        for (let i = score; i > 0; i -= lowbit(i)) {
            count += tree[i];
        }
        return count;
    }

    for (const score of current) tree[score]++;
    for (let i = 1; i <= maxScore; i++) {
        const parent = i + lowbit(i);
        if (parent <= maxScore) tree[parent] += tree[i];
    }

    return {
        rank(player) {
            return current.length - prefix(current[player]) + 1;
        },
        changeScore(player, score) {
            if (score === current[player]) return;
            add(current[player], -1);
            add(score, 1);
            current[player] = score;
        }
    };
}

const board = createLeaderboard([8, 6, 5, 4, 3, 2], 8);
console.log(board.rank(4)); // 5
board.changeScore(4, 6);
console.log(board.rank(4)); // 2
console.log(board.rank(1)); // 2

Peter Fenwick’s paper on cumulative frequency tables