A prefix sum array answers “what is the sum from position l to r?” instantly, but every time a value changes the whole array must be rebuilt. A segment tree handles both operations quickly: it answers range queries and updates single values in O(log n) time. It works for sums, minimums, maximums and many other combinations, which makes it one of the most useful structures for competitive programming and for systems that track live statistics.
In this lesson you will learn
- How a segment tree splits an array into halves
- Storing the tree in an array with children at 2i and 2i + 1
- Building, querying and updating in C
- Range minimum queries with the same structure
- When to use a segment tree instead of simpler tools
You should know recursion and binary trees.
A Segment Tree for Range Sums
#include <stdio.h>
#define N 8
static int a[N] = {5, 3, 8, 6, 1, 4, 7, 2};
static int tree[4 * N]; /* 4n is always enough space for a segment tree */
/* Build: node covers a[lo..hi]; its children cover the two halves */
static void build(int node, int lo, int hi) {
if (lo == hi) { tree[node] = a[lo]; return; }
int mid = (lo + hi) / 2;
build(2 * node, lo, mid);
build(2 * node + 1, mid + 1, hi);
tree[node] = tree[2 * node] + tree[2 * node + 1];
}
/* Sum of a[l..r] */
static int query(int node, int lo, int hi, int l, int r) {
if (r < lo || hi < l) return 0; /* no overlap */
if (l <= lo && hi <= r) return tree[node]; /* fully inside: use the stored sum */
int mid = (lo + hi) / 2;
return query(2 * node, lo, mid, l, r) + query(2 * node + 1, mid + 1, hi, l, r);
}
/* Set a[pos] = value and fix the sums on the path to the root */
static void update(int node, int lo, int hi, int pos, int value) {
if (lo == hi) { a[pos] = value; tree[node] = value; return; }
int mid = (lo + hi) / 2;
if (pos <= mid) update(2 * node, lo, mid, pos, value);
else update(2 * node + 1, mid + 1, hi, pos, value);
tree[node] = tree[2 * node] + tree[2 * node + 1];
}
int main(void) {
build(1, 0, N - 1);
printf("root (sum of all) = %d, left half = %d, right half = %d\n", tree[1], tree[2], tree[3]);
printf("sum a[2..5] = %d\n", query(1, 0, N - 1, 2, 5));
printf("sum a[0..7] = %d\n", query(1, 0, N - 1, 0, 7));
update(1, 0, N - 1, 4, 10); /* a[4]: 1 -> 10 */
printf("after a[4] = 10: sum a[2..5] = %d, total = %d\n", query(1, 0, N - 1, 2, 5), tree[1]);
return 0;
}
Output
root (sum of all) = 36, left half = 22, right half = 14
sum a[2..5] = 19
sum a[0..7] = 36
after a[4] = 10: sum a[2..5] = 28, total = 45
- Every node covers a range of the array. The root (node 1) covers everything; its children cover the left and right halves, and so on until each leaf covers a single element.
- The tree is stored in a plain array like a heap: node
ihas children2iand2i + 1. An array of size4nis always large enough. buildfills the leaves with the array values and each parent with the sum of its two children: O(n).queryhas three cases. If the node’s range is completely outside [l, r], it adds nothing. If it is completely inside, the stored sum is used at once. Otherwise both children are asked. Only O(log n) nodes are visited.updatechanges one leaf and recomputes the sums on the path back to the root: O(log n). After settinga[4] = 10, both the range sum and the total grow by 9.
Range Minimum Queries
#include <stdio.h>
#include <limits.h>
#define N 10
/* A segment tree for range MINIMUM: same shape, different combine step */
static int a[N] = {42, 37, 55, 29, 61, 33, 48, 25, 70, 39}; /* daily temperatures x 10 */
static int tree[4 * N];
static int min2(int x, int y) { return x < y ? x : y; }
static void build(int node, int lo, int hi) {
if (lo == hi) { tree[node] = a[lo]; return; }
int mid = (lo + hi) / 2;
build(2 * node, lo, mid);
build(2 * node + 1, mid + 1, hi);
tree[node] = min2(tree[2 * node], tree[2 * node + 1]);
}
static int query(int node, int lo, int hi, int l, int r) {
if (r < lo || hi < l) return INT_MAX; /* neutral value for min */
if (l <= lo && hi <= r) return tree[node];
int mid = (lo + hi) / 2;
return min2(query(2 * node, lo, mid, l, r), query(2 * node + 1, mid + 1, hi, l, r));
}
static void update(int node, int lo, int hi, int pos, int value) {
if (lo == hi) { tree[node] = value; return; }
int mid = (lo + hi) / 2;
if (pos <= mid) update(2 * node, lo, mid, pos, value);
else update(2 * node + 1, mid + 1, hi, pos, value);
tree[node] = min2(tree[2 * node], tree[2 * node + 1]);
}
int main(void) {
build(1, 0, N - 1);
int ranges[][2] = { {0, 2}, {2, 6}, {5, 9}, {0, 9} };
for (int i = 0; i < 4; i++)
printf("min of days %d..%d = %d\n", ranges[i][0], ranges[i][1],
query(1, 0, N - 1, ranges[i][0], ranges[i][1]));
update(1, 0, N - 1, 7, 50); /* correct day 7's reading */
printf("after fixing day 7: min of days 5..9 = %d\n", query(1, 0, N - 1, 5, 9));
return 0;
}
Output
min of days 0..2 = 37
min of days 2..6 = 29
min of days 5..9 = 25
min of days 0..9 = 25
after fixing day 7: min of days 5..9 = 33
- Changing two things turns the sum tree into a minimum tree: the combine step becomes
min2, and a range outside the query returnsINT_MAX, the neutral value that never wins a minimum. - Any operation that combines two halves into one answer works the same way: maximum, greatest common divisor, bitwise OR, or the product modulo a number.
- Correcting day 7 from 25 to 50 changes the minimum of days 5 to 9 from 25 to 33, and only the nodes on one root-to-leaf path were recomputed.
Range Query Structures Compared
| Structure | Range query | Point update | Notes |
|---|---|---|---|
| Plain array | O(n) | O(1) | Fine for rare queries |
| Prefix sum array | O(1) | O(n) | Sums only; best when values never change |
| Fenwick tree | O(log n) | O(log n) | Short code; best for sums |
| Segment tree | O(log n) | O(log n) | Sums, min, max and more; supports range updates |
Common Mistakes
- Allocating only
2nnodes for this recursive layout; use4n. - Returning 0 for out-of-range parts of a minimum query, which wrongly wins. Use the neutral value for the operation.
- Forgetting to update the parents after changing a leaf.
- Mixing 0-based array indexes with the 1-based node numbers.
Practice Exercises
Exercise 1. Change the sum tree into a range maximum tree.
Show answer
Combine with max instead of +, and return INT_MIN for ranges outside the query.
Exercise 2. About how many nodes does one query visit for an array of 1,000,000 elements?
Show answer
The tree is about log2(1,000,000) ≈ 20 levels tall, and a query visits at most a few nodes per level, so under about 80 nodes, compared with up to a million for a simple loop.
Frequently Asked Questions
Can a segment tree add a value to a whole range at once?
Yes, with lazy propagation: a node stores a pending addition for its whole range and passes it to its children only when they are visited. Both range updates and range queries then take O(log n).
Why is the array size 4n?
When n is not a power of two, the recursive splitting can produce a tree whose node numbers go beyond 2n. 4n is a simple bound that is always enough.
Summary
- A segment tree stores combined values for halves, quarters and so on.
- Build in O(n); query and update in O(log n).
- Change the combine step and neutral value for min, max or other operations.
- Store it in an array of size 4n with children at 2i and 2i + 1.
