Segment Trees & Fenwick Trees
Week 9
Segment Tree
Supports range queries and point updates in O(log n).
Array: [2, 4, 6, 8, 10]
Segment tree (range sum):
30
/ \
12 18
/ \ / \
2 10 14 4
/ \ / \
4 6 8 6| Operation | Complexity |
|---|---|
| Build | O(n) |
| Range query | O(log n) |
| Point update | O(log n) |
| Range update + lazy | O(log n) |
Fenwick Tree (Binary Indexed Tree)
Simpler implementation, supports prefix sum queries and point updates.
class BIT {
constructor(n) { this.tree = Array(n + 1).fill(0); }
update(i, delta) {
for (; i < this.tree.length; i += i & (-i))
this.tree[i] += delta;
}
query(i) { // prefix sum [1..i]
let sum = 0;
for (; i > 0; i -= i & (-i))
sum += this.tree[i];
return sum;
}
rangeQuery(l, r) { return this.query(r) - this.query(l - 1); }
}Key Problems
| # | Problem | Structure | Difficulty |
|---|---|---|---|
| 1 | Range Sum Query Mutable | BIT / Segment Tree | Medium |
| 2 | Count of Smaller Numbers After Self | BIT | Hard |
| 3 | Range Minimum Query | Segment Tree | Medium |
| 4 | The Skyline Problem | Segment Tree / heap | Hard |
Real-World Frontend Application
Segment trees are used when you have a large dataset that updates frequently and you need to query ranges. For example, a real-time analytics dashboard showing total sales between two arbitrary dates, where new sales are constantly streaming in via WebSockets.
Segment Tree (Range Sums)
1 / 2
Sum(0-3)
10
Sum(0-1)
3
Sum(2-3)
7
A[0]: 1
A[1]: 2
A[2]: 3
A[3]: 4
Leaf nodes store array elements. Internal nodes store the sum of their children.