AlgoTales · Roadmap

Range query

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

Where you will meet this in real life

A range query on a Fenwick tree gets the total between two positions by taking the prefix total up to the right end and subtracting the prefix total before the left end. It gives range answers on data that is still changing.

Practical use cases

  • Web app: Warehouse stock between two shelves. An inventory screen lets staff pick shelf 120 to shelf 340 and shows total items there, while pickers constantly add and remove stock. Two prefix queries and one subtraction answer instantly, and each stock change updates only a few cells.
  • Web app: Hourly order counts for a time window. A dashboard counts orders per minute and lets the owner pick "10:15 to 11:40". Even as new orders keep arriving, the total for any window is two prefix reads, so the chart never waits. Each new order changes only a few stored cells.
  • System: Game scoreboards and range-sum problems. Games summing points across a band of players, and the classic "Range Sum Query - Mutable" problem, rely on exactly this pair of prefix reads. Both the updates and the range questions stay fast, which is why this pair is a standard tool in contests and apps.

The story: Zoya's Wedding Plates

Zoya's uncle runs a catering company, and on wedding days Zoya stands at the head table with a clipboard. There are 8 serving tables in a row, and servers keep shouting new plate counts: "Table 3 got ten more!" She keeps helper boxes just like Mrs. Sharma's switchboard: every update takes only a few quick additions.

Then the bride's father asks, "How many plates went out to tables 3 to 6?" Zoya froze. Her boxes always give totals that begin at table 1. Nothing starts in the middle.

Mira whispered, "Remember the passbook? We never needed a range-sum box. A range is a long prefix minus a short prefix." Zoya computed the total for tables 1 to 6 (two boxes), then the total for tables 1 to 2 (one box), and subtracted. Whatever both totals shared, tables 1 and 2, vanished, leaving exactly tables 3 to 6. Two small walks and one subtraction answered a question about a range in the middle. That is a Fenwick range query, and updates still stay quick.

How to spot this problem, and where you need it

You need sums over arbitrary ranges while individual values keep changing, so neither a static prefix list nor a plain loop works well.

Signs you need it

  • Both operations appear together: change one value and ask for the sum of a range.
  • Static prefix sums gave fast queries but updates became painfully slow.
  • A loop per query is fine for 1,000 items but not for 1,000,000.
  • The problem says "mutable array" with range sum.

Where to use it in a project

  • Live inventory, stock and capacity screens with range filters.
  • Time-bucketed counters (per minute, hour) with selectable windows.

The solution

Keep the data in a Fenwick tree. To get the total from a to b, compute the prefix total up to b and subtract the prefix total up to a minus 1. To change a value, do a point update. Both operations cost only about as many steps as the number has bits, so queries and updates stay fast together.

Payoff: Before: looping over up to a million entries per query. After: about 40 cell reads per query and 20 per update.

Explain it like I am 8

To know how many sweets are between the 3rd and 6th jar, count all sweets from the first jar to the 6th, then count all sweets from the first jar to the 2nd, and take the second number away. The sweets in the first two jars are in both counts, so they disappear.

How it works, step by step

  1. Want shelves l to r? Compute prefix(r) using the walk-down you already know.
  2. Compute prefix(l - 1) the same way. When l is 1 this is prefix(0), which is just 0.
  3. Subtract: prefix(r) - prefix(l - 1).
  4. Updates are untouched. A point update still climbs up, so you can mix updates and range questions as long as you like.
  5. Total cost: two short walks, each as long as the number of switches in the index.

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; }
}

function prefixSum(array $t, int $i): int {
    $sum = 0;
    for (; $i > 0; $i -= lowbit($i)) { $sum += $t[$i]; }
    return $sum;
}

// Tables l..r inclusive (1-based): long prefix minus short prefix
function rangeSum(array $t, int $l, int $r): int {
    return prefixSum($t, $r) - prefixSum($t, $l - 1);
}

$plates = [5, 3, 7, 2, 6, 4, 1, 8];
$t = array_fill(0, count($plates) + 1, 0);
foreach ($plates as $k => $v) { fenwickAdd($t, $k + 1, $v); }

echo rangeSum($t, 3, 6) . PHP_EOL;      // 7+2+6+4 = 19
echo rangeSum($t, 1, 8) . PHP_EOL;      // everything = 36

fenwickAdd($t, 3, 10);                  // ten more plates arrive at table 3
echo rangeSum($t, 3, 6) . PHP_EOL;      // 29

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; }
}

function prefixSum(t, i) {
  let sum = 0;
  for (; i > 0; i -= lowbit(i)) { sum += t[i]; }
  return sum;
}

// Tables l..r inclusive (1-based): long prefix minus short prefix
function rangeSum(t, l, r) {
  return prefixSum(t, r) - prefixSum(t, l - 1);
}

const plates = [5, 3, 7, 2, 6, 4, 1, 8];
const t = new Array(plates.length + 1).fill(0);
plates.forEach((v, k) => fenwickAdd(t, k + 1, v));

console.log(rangeSum(t, 3, 6));         // 7+2+6+4 = 19
console.log(rangeSum(t, 1, 8));         // everything = 36

fenwickAdd(t, 3, 10);                   // ten more plates arrive at table 3
console.log(rangeSum(t, 3, 6));         // 29

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; }
    }

    static int prefixSum(int[] t, int i) {
        int sum = 0;
        for (; i > 0; i -= lowbit(i)) { sum += t[i]; }
        return sum;
    }

    // Tables l..r inclusive (1-based): long prefix minus short prefix
    static int rangeSum(int[] t, int l, int r) {
        return prefixSum(t, r) - prefixSum(t, l - 1);
    }

    public static void main(String[] args) {
        int[] plates = {5, 3, 7, 2, 6, 4, 1, 8};
        int[] t = new int[plates.length + 1];
        for (int k = 0; k < plates.length; k++) { fenwickAdd(t, k + 1, plates[k]); }

        System.out.println(rangeSum(t, 3, 6));      // 7+2+6+4 = 19
        System.out.println(rangeSum(t, 1, 8));      // everything = 36

        fenwickAdd(t, 3, 10);                       // ten more plates arrive at table 3
        System.out.println(rangeSum(t, 3, 6));      // 29
    }
}

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
	}
}

func prefixSum(t []int, i int) int {
	sum := 0
	for ; i > 0; i -= lowbit(i) {
		sum += t[i]
	}
	return sum
}

// rangeSum totals tables l..r inclusive (1-based): long prefix minus short prefix.
func rangeSum(t []int, l, r int) int {
	return prefixSum(t, r) - prefixSum(t, l-1)
}

func main() {
	plates := []int{5, 3, 7, 2, 6, 4, 1, 8}
	t := make([]int, len(plates)+1)
	for k, v := range plates {
		fenwickAdd(t, k+1, v)
	}

	fmt.Println(rangeSum(t, 3, 6)) // 7+2+6+4 = 19
	fmt.Println(rangeSum(t, 1, 8)) // everything = 36

	fenwickAdd(t, 3, 10)           // ten more plates arrive at table 3
	fmt.Println(rangeSum(t, 3, 6)) // 29
}

Time: O(log n) per range query and per update · Extra space: O(n). Two short walks plus a subtraction. Updates stay just as cheap, which a plain prefix array cannot offer.

Watch out for

  • Calling prefixSum(l) instead of prefixSum(l - 1), which silently drops shelf l.
  • Trying to use the same subtraction trick for minimum or maximum. It works only for sums (things you can undo).
  • Mixing 0-based user indexes with the 1-based Fenwick array.

Quick check

  1. Range sum of tables 3 to 6 equals...
    • prefix(6) - prefix(3)
    • prefix(6) - prefix(2)
    • prefix(3) + prefix(6)
  2. Why does subtraction work?
    • Boxes are sorted
    • Because the numbers are small
    • The shared left part appears in both prefixes and cancels
  3. Would this same subtraction trick give a range minimum?
    • Yes, with prefix minimums
    • No, you cannot "undo" a minimum
    • Only for sorted data