Range sum
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Range sum with a segment tree is the specific job of totalling a stretch of values while they change. A compact bottom-up version of the tree does this with a simple loop in which two pointers climb from the two ends of the range.
Practical use cases
- Web app: Interactive chart totals. On a finance page, the user drags across a bar chart and sees the sum of the selected bars. A tight loop climbing the tree from both ends returns the total in a few steps, so the number updates in step with the mouse.
- Web app: Expense tracker with live edits. In a budgeting app, the user edits one expense and immediately sees the total for any selected week range. The update fixes a few blocks and the range sum reads a few blocks, so edits feel instant.
- System: Online judges and low-level libraries. Contest solutions and performance-focused libraries use this compact version because it is short, has little overhead and runs very fast on large inputs. There is no recursion and almost no extra memory, so even large inputs finish well within the time limit.
The story: Two Climbers and the Water Tanker
In Mira's mohalla the water tanker visits 8 streets and the society secretary logs the litres each street got. The log is stored as a segment tree: the bottom row is the streets, and each circle above holds the total of the two circles under it. The secretary now needs an answer to "How many litres for streets 1 to 6?" and she wants it fast and without any recursion.
Kabir had a picture in his head: two climbers on a ladder. "Put one climber at the left end of the range and one at the right end of the bottom row. Each climber looks at their own circle. The left climber asks: am I a right child? If yes, my parent would drag in a street on my left that nobody asked for, so I take my own number and step right. The right climber asks the opposite: am I a left child? Then my parent would drag in a street on my right, so I take my number and step left."
After that, both climbers jump to their parents and ask again. They keep climbing until they cross each other. Whatever they picked up on the way is the answer. For streets 1 to 6 they collected 3, then 1, then 9, then 10: four circles, total 23. This version of the segment tree range sum is short, quick, and wonderfully easy to write.
How to spot this problem, and where you need it
You need many total-over-a-range answers on data that also changes, and you want a short, fast implementation without heavy recursion.
Signs you need it
- The task combines "update one position" with "sum of positions l to r".
- Recursive solutions are too slow or too memory hungry on your platform.
- Time limits are tight or the list holds hundreds of thousands of items.
- You only need sums (or another simple combinable value), not complex range changes.
Where to use it in a project
- Interactive charts and spreadsheets that show totals of a selection.
- Performance-sensitive backends and contest solutions that need short, quick code.
The solution
Store the values in the leaves of an array-based tree. For a range, put one pointer at the left end and one at the right end. Whenever the left pointer is a right child, add its node and move on; whenever the right pointer is a left child, add its node. Then both move up to their parents. Continue until they meet.
Payoff: Before: adding up to 500,000 values per query. After: about 40 node reads.
Explain it like I am 8
Imagine two friends standing at the two ends of a row of boxes, each holding a bag. A friend only picks up a number when stepping to the parent would grab an extra box they do not want. After each round they both move one floor up the ladder. When they cross paths, the bags together hold exactly the answer.
How it works, step by step
- Build the tree in an array with the leaves in the second half. For n items, leaf number i lives at position
n + i, and the circle at k has children2kand2k + 1. - Place two climbers at the bottom: left at
l + n, right atr + n. - Left climber: if its number is odd (a right child), add it to the sum and step right by one.
- Right climber: if its number is even (a left child), add it to the sum and step left by one.
- Climb: both divide their number by 2 (go to the parent). Repeat while left is not past right.
The code in four languages
PHP
<?php
class SumTree {
private array $t;
private int $n;
public function __construct(array $a) {
$this->n = count($a);
$this->t = array_fill(0, 2 * $this->n, 0);
foreach ($a as $i => $v) $this->t[$this->n + $i] = $v; // leaves live in the second half
for ($k = $this->n - 1; $k >= 1; $k--) {
$this->t[$k] = $this->t[2 * $k] + $this->t[2 * $k + 1]; // each circle pools its two children
}
}
// Change one position and repair upward
public function set(int $i, int $v): void {
$k = $i + $this->n;
$this->t[$k] = $v;
for ($k = intdiv($k, 2); $k >= 1; $k = intdiv($k, 2)) {
$this->t[$k] = $this->t[2 * $k] + $this->t[2 * $k + 1];
}
}
// Sum of positions l..r (inclusive): two climbers from the bottom
public function sum(int $l, int $r): int {
$l += $this->n;
$r += $this->n;
$total = 0;
while ($l <= $r) {
if ($l % 2 === 1) $total += $this->t[$l++]; // left climber is a right child: take it, step right
if ($r % 2 === 0) $total += $this->t[$r--]; // right climber is a left child: take it, step left
$l = intdiv($l, 2); // both climb to their parents
$r = intdiv($r, 2);
}
return $total;
}
}
$litres = new SumTree([5, 3, 7, 2, 6, 4, 1, 8]);
echo $litres->sum(1, 6) . PHP_EOL; // 3+7+2+6+4+1 = 23
echo $litres->sum(0, 7) . PHP_EOL; // 36
$litres->set(2, 10); // street 2 gets 3 more
echo $litres->sum(1, 6) . PHP_EOL; // 26JavaScript
class SumTree {
constructor(a) {
this.n = a.length;
this.t = new Array(2 * this.n).fill(0);
a.forEach((v, i) => { this.t[this.n + i] = v; }); // leaves live in the second half
for (let k = this.n - 1; k >= 1; k--) {
this.t[k] = this.t[2 * k] + this.t[2 * k + 1]; // each circle pools its two children
}
}
// Change one position and repair upward
set(i, v) {
let k = i + this.n;
this.t[k] = v;
for (k >>= 1; k >= 1; k >>= 1) {
this.t[k] = this.t[2 * k] + this.t[2 * k + 1];
}
}
// Sum of positions l..r (inclusive): two climbers from the bottom
sum(l, r) {
l += this.n;
r += this.n;
let total = 0;
while (l <= r) {
if (l % 2 === 1) total += this.t[l++]; // left climber is a right child: take it, step right
if (r % 2 === 0) total += this.t[r--]; // right climber is a left child: take it, step left
l >>= 1; // both climb to their parents
r >>= 1;
}
return total;
}
}
const litres = new SumTree([5, 3, 7, 2, 6, 4, 1, 8]);
console.log(litres.sum(1, 6)); // 3+7+2+6+4+1 = 23
console.log(litres.sum(0, 7)); // 36
litres.set(2, 10); // street 2 gets 3 more
console.log(litres.sum(1, 6)); // 26Java
public class Main {
static class SumTree {
int[] t;
int n;
SumTree(int[] a) {
n = a.length;
t = new int[2 * n];
for (int i = 0; i < n; i++) t[n + i] = a[i]; // leaves live in the second half
for (int k = n - 1; k >= 1; k--) {
t[k] = t[2 * k] + t[2 * k + 1]; // each circle pools its two children
}
}
// Change one position and repair upward
void set(int i, int v) {
int k = i + n;
t[k] = v;
for (k /= 2; k >= 1; k /= 2) {
t[k] = t[2 * k] + t[2 * k + 1];
}
}
// Sum of positions l..r (inclusive): two climbers from the bottom
int sum(int l, int r) {
l += n;
r += n;
int total = 0;
while (l <= r) {
if (l % 2 == 1) total += t[l++]; // left climber is a right child: take it, step right
if (r % 2 == 0) total += t[r--]; // right climber is a left child: take it, step left
l /= 2; // both climb to their parents
r /= 2;
}
return total;
}
}
public static void main(String[] args) {
SumTree litres = new SumTree(new int[]{5, 3, 7, 2, 6, 4, 1, 8});
System.out.println(litres.sum(1, 6)); // 3+7+2+6+4+1 = 23
System.out.println(litres.sum(0, 7)); // 36
litres.set(2, 10); // street 2 gets 3 more
System.out.println(litres.sum(1, 6)); // 26
}
}Go
package main
import "fmt"
type SumTree struct {
t []int
n int
}
func NewSumTree(a []int) *SumTree {
n := len(a)
s := &SumTree{t: make([]int, 2*n), n: n}
copy(s.t[n:], a) // leaves live in the second half
for k := n - 1; k >= 1; k-- {
s.t[k] = s.t[2*k] + s.t[2*k+1] // each circle pools its two children
}
return s
}
// Set changes one position and repairs upward.
func (s *SumTree) Set(i, v int) {
k := i + s.n
s.t[k] = v
for k /= 2; k >= 1; k /= 2 {
s.t[k] = s.t[2*k] + s.t[2*k+1]
}
}
// Sum adds positions l..r (inclusive): two climbers from the bottom.
func (s *SumTree) Sum(l, r int) int {
l += s.n
r += s.n
total := 0
for l <= r {
if l%2 == 1 { // left climber is a right child: take it, step right
total += s.t[l]
l++
}
if r%2 == 0 { // right climber is a left child: take it, step left
total += s.t[r]
r--
}
l /= 2 // both climb to their parents
r /= 2
}
return total
}
func main() {
litres := NewSumTree([]int{5, 3, 7, 2, 6, 4, 1, 8})
fmt.Println(litres.Sum(1, 6)) // 3+7+2+6+4+1 = 23
fmt.Println(litres.Sum(0, 7)) // 36
litres.Set(2, 10) // street 2 gets 3 more
fmt.Println(litres.Sum(1, 6)) // 26
}Time: O(log n) per query · Extra space: O(n). Each loop round climbs one level, and every round picks up at most two circles.
Watch out for
- Mixing inclusive and exclusive right ends. The version here uses inclusive for both; check your loop condition (
l <= r). - Forgetting to move both climbers up after the checks, which makes an infinite loop.
- Using this simple loop for operations where order matters (like string joins) without care. Sums, minimums and maximums are safe.
Quick check
- When does the left climber take its circle?
- When it is a right child (odd number)
- When it is a left child (even number)
- Always
- When does the loop end?
- When both climbers reach the root
- After exactly 4 rounds
- When the left climber passes the right climber
- Where are the leaves stored in this bottom-up array?
- At positions n to 2n-1
- At positions 0 to n-1
- In a separate list