Prefix query
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A prefix query in a Fenwick tree returns the total of everything from the first position up to a chosen position. It reads a few helper cells that together cover the range end to end, so even huge lists need only a handful of reads.
Practical use cases
- Web app: Your rank in an online exam. After submitting, a student sees "you scored better than 84 percent". The portal keeps a count of how many people got each score, and a prefix query adds up the counts below the student score. With 1,000 possible marks that is only about 10 reads, however many people took the test.
- Web app: Tickets sold so far for a show. A booking site wants "seats sold up to row 20" while bookings keep coming. A prefix query over the row counters gives it instantly, without re-adding every row each time someone books.
- System: Analytics and order statistics. Counting "how many values are smaller than x" is the core of percentile and rank reports and of counting out-of-order pairs in analytics code. Rank and percentile pages work only because each cumulative count takes about as many steps as the index has bits.
The story: Tickets at Gate Number Seven
Kabir loves watching cricket at the stadium, and this season he got a job at the ticket office. The stadium has 8 gates, and tickets sold at each gate change all day. The manager keeps shouting: "How many tickets so far for gates 1 to 7?" The old running-total sheet could not keep up with the changing numbers, so Kabir used Mrs. Sharma's switchboard idea: helper boxes, where each box is in charge of a small territory of gates.
But how do you read the total? Kabir was nervous: adding all 7 gates one by one defeats the purpose. Grandpa Bhaskar tapped the switchboard. "Start from gate 7. Its helper covers just gate 7, so take that box. Now switch off the lowest ON switch of 7. The board now shows 6. The box for 6 covers gates 5 and 6, which are exactly the gates just before gate 7's territory. Take it. Switch off its lowest switch and you land on 4, whose helper covers gates 1 to 4."
Kabir took boxes 7, 6 and 4, and their numbers tiled gates 1 to 7 perfectly, with no gap and no overlap. Switching off the last switch of 4 gave 0, which meant nothing was left. Three boxes instead of seven gates. For a thousand gates, it would be about ten boxes. This walk is called a Fenwick prefix query.
How to spot this problem, and where you need it
You need the running total or count up to a certain point while the data keeps changing, and recalculating from the start for every question is too slow.
Signs you need it
- The question reads "how many are less than or equal to x" or "total up to index i".
- The data keeps changing so a one-time prefix list goes stale.
- You show ranks, percentiles or cumulative counts live.
- A loop from the start to i runs for every request.
Where to use it in a project
- Exam, contest and leaderboard ranking pages for students.
- Live cumulative reports such as total bookings, orders or revenue up to a point.
The solution
In a Fenwick tree, start at your position i and add that cell. Then drop the lowest set bit of i (move to i minus its lowest 1-bit) and add that cell, repeating until the index becomes zero. The cells visited cover the whole prefix with no overlap, and there are only as many as the number of bits in i.
Payoff: Before: adding up to 100,000 counters per rank request. After: about 17 reads.
Explain it like I am 8
Imagine a row of toy boxes with different sizes: some hold 1 shelf of toys, some 2, some 4. To count the toys on shelves 1 to 7, pick the right boxes so that they cover the shelves end to end. Start from the last shelf, grab its box, then step to where that box started, and repeat. The light switches show you each step: switch off the lowest ON light.
How it works, step by step
- Start at the last shelf you care about, call it i.
- Take box i and add its value to your running total.
- Switch off the lowest ON switch of i:
i = i - (value of the lowest ON switch), in codei -= i & -i. This jumps to the end of the territory just before. - Repeat while i is bigger than 0.
- Result: the running total is the sum of shelves 1 to the original i.
The code in four languages
PHP
<?php
function lowbit(int $i): int { return $i & -$i; }
function fenwickAdd(array &$t, int $i, int $delta): void {
$n = count($t) - 1;
for (; $i <= $n; $i += lowbit($i)) {
$t[$i] += $delta;
}
}
// Total of shelves 1..i : take a box, switch off its lowest ON switch, repeat
function prefixSum(array $t, int $i): int {
$sum = 0;
while ($i > 0) {
$sum += $t[$i]; // this box covers a small territory ending at i
$i -= lowbit($i); // jump to where that territory started (minus one)
}
return $sum;
}
$gates = [5, 3, 7, 2, 6, 4, 1, 8];
$t = array_fill(0, count($gates) + 1, 0);
foreach ($gates as $k => $v) {
fenwickAdd($t, $k + 1, $v);
}
echo prefixSum($t, 7) . PHP_EOL; // 5+3+7+2+6+4+1 = 28 (boxes 7, 6, 4)
echo prefixSum($t, 4) . PHP_EOL; // 5+3+7+2 = 17 (box 4 only)
echo prefixSum($t, 8) . PHP_EOL; // everything = 36 (box 8 only)JavaScript
function lowbit(i) { return i & -i; }
function fenwickAdd(t, i, delta) {
const n = t.length - 1;
for (; i <= n; i += lowbit(i)) {
t[i] += delta;
}
}
// Total of shelves 1..i : take a box, switch off its lowest ON switch, repeat
function prefixSum(t, i) {
let sum = 0;
while (i > 0) {
sum += t[i]; // this box covers a small territory ending at i
i -= lowbit(i); // jump to where that territory started (minus one)
}
return sum;
}
const gates = [5, 3, 7, 2, 6, 4, 1, 8];
const t = new Array(gates.length + 1).fill(0);
gates.forEach((v, k) => fenwickAdd(t, k + 1, v));
console.log(prefixSum(t, 7)); // 5+3+7+2+6+4+1 = 28 (boxes 7, 6, 4)
console.log(prefixSum(t, 4)); // 5+3+7+2 = 17 (box 4 only)
console.log(prefixSum(t, 8)); // everything = 36 (box 8 only)Java
public class Main {
static int lowbit(int i) { return i & -i; }
static void fenwickAdd(int[] t, int i, int delta) {
int n = t.length - 1;
for (; i <= n; i += lowbit(i)) {
t[i] += delta;
}
}
// Total of shelves 1..i : take a box, switch off its lowest ON switch, repeat
static int prefixSum(int[] t, int i) {
int sum = 0;
while (i > 0) {
sum += t[i]; // this box covers a small territory ending at i
i -= lowbit(i); // jump to where that territory started (minus one)
}
return sum;
}
public static void main(String[] args) {
int[] gates = {5, 3, 7, 2, 6, 4, 1, 8};
int[] t = new int[gates.length + 1];
for (int k = 0; k < gates.length; k++) {
fenwickAdd(t, k + 1, gates[k]);
}
System.out.println(prefixSum(t, 7)); // 5+3+7+2+6+4+1 = 28 (boxes 7, 6, 4)
System.out.println(prefixSum(t, 4)); // 5+3+7+2 = 17 (box 4 only)
System.out.println(prefixSum(t, 8)); // everything = 36 (box 8 only)
}
}Go
package main
import "fmt"
func lowbit(i int) int { return i & -i }
func fenwickAdd(t []int, i, delta int) {
n := len(t) - 1
for ; i <= n; i += lowbit(i) {
t[i] += delta
}
}
// prefixSum totals shelves 1..i: take a box, switch off its lowest ON switch, repeat.
func prefixSum(t []int, i int) int {
sum := 0
for i > 0 {
sum += t[i] // this box covers a small territory ending at i
i -= lowbit(i) // jump to where that territory started (minus one)
}
return sum
}
func main() {
gates := []int{5, 3, 7, 2, 6, 4, 1, 8}
t := make([]int, len(gates)+1)
for k, v := range gates {
fenwickAdd(t, k+1, v)
}
fmt.Println(prefixSum(t, 7)) // 5+3+7+2+6+4+1 = 28 (boxes 7, 6, 4)
fmt.Println(prefixSum(t, 4)) // 5+3+7+2 = 17 (box 4 only)
fmt.Println(prefixSum(t, 8)) // everything = 36 (box 8 only)
}Time: O(log n) per query · Extra space: O(n). Each hop switches one light off, so you take at most as many boxes as there are lights in the number.
Watch out for
- Climbing up (adding the lowest switch) instead of walking down (subtracting it). Updates climb, queries descend.
- Looping until
i >= 0. Stop at 0: box 0 does not exist. - Asking for a 0-based index. Shelf numbers start at 1; convert before calling.
Quick check
- To get the total of shelves 1..6, which boxes are taken?
- 6 and 5
- 6, 5 and 4
- 6 and 4
- What happens to the number after taking box i?
- It gets the lowest ON switch added
- It loses its lowest ON switch
- It is divided by two
- When do we stop?
- When i reaches n
- After 4 steps
- When i reaches 0