Segment trees
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A segment tree is a binary tree where each node stores an aggregated value over a specific subarray interval. We start with naive linear scans to see why dynamic range queries time out, and then build the segment tree.
From Linear Scans to a Binary Tree of Intervals
A segment tree is a binary tree where each node stores an answer, such as a sum, for a range of the array, so range queries and updates both take O(log n).
Suppose you have an array of N numbers and must support both range sum queries and element updates. A naive array takes O(N) per query and O(1) per update; a prefix sum takes O(1) per query and O(N) per update.
A segment tree breaks this deadlock by organizing the array into a binary tree. The root node represents the entire array [0, N - 1]. Each node recursively splits its interval in half: left child covers [start, mid] and right child covers [mid + 1, end].
Leaves represent single elements [i, i]. Any arbitrary range query [L, R] decomposes into at most 2 * ceil(log2 N) canonical tree nodes, allowing queries and point updates to execute in O(log N) time.
Step by step
Step 1 of 7
| Row | Node 1 | Node 2 | Node 3 | Node 4 | Node 5 | Node 6 | Node 7 |
|---|---|---|---|---|---|---|---|
| Node Index | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| Interval | [0..3] | [0..1] | [2..3] | [0..0] | [1..1] | [2..2] | [3..3] |
| Sum Value | 1 | 3 |
The Array Representation and 4N Sizing
Instead of allocating pointer-heavy TreeNode objects with heap overhead, segment trees are traditionally stored in a flat 1D array, identical to binary heaps.
Example 1 · Reading a segment tree array: O(N) build
public class SegmentTreeArrayLayoutDemo { static class SimpleSegTree { int[] tree; int n; SimpleSegTree(int[] arr) { n = arr.length; tree = new int[4 * n]; build(arr, 1, 0, n - 1); } void build(int[] arr, int node, int s, int e) { if (s == e) { tree[node] = arr[s]; return; } int mid = (s + e) / 2; build(arr, 2 * node, s, mid); build(arr, 2 * node + 1, mid + 1, e); tree[node] = tree[2 * node] + tree[2 * node + 1]; } int query(int l, int r) { return query(1, 0, n - 1, l, r); } int query(int node, int s, int e, int l, int r) { if (r < s || l > e) return 0; if (l <= s && e <= r) return tree[node]; int mid = (s + e) / 2; return query(2 * node, s, mid, l, r) + query(2 * node + 1, mid + 1, e, l, r); } }
public static void main(String[] args) { int[] arr = {1, 3, 5, 7}; SimpleSegTree st = new SimpleSegTree(arr); System.out.println("Root covers [0..3] sum: " + st.query(0, 3)); System.out.println("Left child covers [0..1] sum: " + st.query(0, 1)); System.out.println("Right child covers [2..3] sum: " + st.query(2, 3)); }}Root covers [0..3] sum: 16 Left child covers [0..1] sum: 4 Right child covers [2..3] sum: 12
What this code does
- Root stores sum 16 of the full array.
- Left half [0..1] stores 1 + 3 = 4.
- Right half [2..3] stores 5 + 7 = 12.
Root is stored at index 1 (or 0). For a node at index node: its left child is at 2 * node, and its right child is at 2 * node + 1. The parent is located at node / 2. How much array space is required? If N is a power of 2, the tree has 2N - 1 nodes. If N is not a power of 2, the bottom level can extend to almost 4N. Allocating tree = new int[4 * N] is the universal competitive standard to prevent out-of-bounds indexing.
Find the bug
Find the segment tree bug
Tap the line that breaks the tree.
A recursive segment tree is built for any length n.
Round 1 of 3Executing Range Queries and Point Updates
To query [L, R], we start at the root node [start, end]. If the node interval is completely inside [L, R], we return its stored value immediately. If it is completely outside, we return the neutral identity value (0 for sum, infinity for min).
Segment tree query: sum of indexes 1 to 2
Step 1 of 8
- total
- 0
Example 2 · Range sum by scanning, brute force: O(N) query, O(1) update
public class PlainRangeSumDemo { static int query(int[] arr, int left, int right) { int sum = 0; for (int i = left; i <= right; i++) sum += arr[i]; // O(N) per query return sum; }
public static void main(String[] args) { int[] arr = {1, 3, 5, 7}; System.out.println("Sum [1, 2]: " + query(arr, 1, 2)); arr[1] = 10; // O(1) update System.out.println("Sum [1, 2] after update: " + query(arr, 1, 2)); }}Sum [1, 2]: 8 Sum [1, 2] after update: 15
What this code does
- query() loops from left to right and adds each element.
- The update is one assignment: O(1).
- It prints 8 and 15, the same as the segment tree, which balances both costs at O(log N).
Example 3 · Segment tree for range sums, optimal: O(log N) query and update, O(N) space
public class SegmentTreeSumDemo { private int[] tree; private int n;
public SegmentTreeSumDemo(int[] arr) { n = arr.length; tree = new int[4 * n]; build(arr, 1, 0, n - 1); }
private void build(int[] arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; build(arr, 2 * node, start, mid); build(arr, 2 * node + 1, mid + 1, end); tree[node] = tree[2 * node] + tree[2 * node + 1]; }
public void update(int idx, int val) { update(1, 0, n - 1, idx, val); }
private void update(int node, int start, int end, int idx, int val) { if (start == end) { tree[node] = val; return; } int mid = (start + end) / 2; if (idx <= mid) update(2 * node, start, mid, idx, val); else update(2 * node + 1, mid + 1, end, idx, val); tree[node] = tree[2 * node] + tree[2 * node + 1]; }
public int query(int l, int r) { return query(1, 0, n - 1, l, r); }
private int query(int node, int start, int end, int l, int r) { if (r < start || end < l) return 0; // disjoint if (l <= start && end <= r) return tree[node]; // complete overlap int mid = (start + end) / 2; return query(2 * node, start, mid, l, r) + query(2 * node + 1, mid + 1, end, l, r); }
public static void main(String[] args) { int[] arr = {1, 3, 5, 7}; SegmentTreeSumDemo st = new SegmentTreeSumDemo(arr); System.out.println("Sum [1, 2]: " + st.query(1, 2)); st.update(1, 10); // arr becomes {1, 10, 5, 7} System.out.println("Sum [1, 2] after update: " + st.query(1, 2)); }}Sum [1, 2]: 8 Sum [1, 2] after update: 15
What this code does
- Sum [1, 2] covers arr[1] (3) + arr[2] (5) = 8.
- Updating index 1 to 10 changes the sum to 10 + 5 = 15.
- Both query and update execute in strictly O(log N) time.
- Why faster: a query combines at most about 2 · log2(N) ready-made node sums instead of adding every element, and an update fixes one root-to-leaf path.
Example 4 · Segment tree for range minimum: O(log N) per query
public class SegmentTreeRmqDemo { private int[] tree; private int n;
public SegmentTreeRmqDemo(int[] arr) { n = arr.length; tree = new int[4 * n]; build(arr, 1, 0, n - 1); }
private void build(int[] arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; build(arr, 2 * node, start, mid); build(arr, 2 * node + 1, mid + 1, end); tree[node] = Math.min(tree[2 * node], tree[2 * node + 1]); }
public int query(int l, int r) { return query(1, 0, n - 1, l, r); }
private int query(int node, int start, int end, int l, int r) { if (r < start || end < l) return Integer.MAX_VALUE; if (l <= start && end <= r) return tree[node]; int mid = (start + end) / 2; return Math.min(query(2 * node, start, mid, l, r), query(2 * node + 1, mid + 1, end, l, r)); }
public static void main(String[] args) { int[] arr = {5, 2, 8, 1, 9, 3}; SegmentTreeRmqDemo rmq = new SegmentTreeRmqDemo(arr); System.out.println("Min [0, 2]: " + rmq.query(0, 2)); System.out.println("Min [1, 5]: " + rmq.query(1, 5)); System.out.println("Min [4, 5]: " + rmq.query(4, 5)); }}Min [0, 2]: 2 Min [1, 5]: 1 Min [4, 5]: 3
What this code does
- Returns neutral identity Integer.MAX_VALUE when intervals are disjoint.
- Merges results with Math.min to resolve non-invertible range minimums.
- Executes in O(log N) time per query.
If the interval partially overlaps [L, R], we recursively query left and right children and combine their results. At each level of the tree, at most four nodes are visited, guaranteeing an O(log N) query time. To update an element at index idx, we search down to leaf [idx, idx], update its value, and backtrack up to the root, recalculating each ancestor node in O(log N) time.
Next step
Check your understanding
10 quick questions