Data Structures · Visualization
Segment Tree: Range Sum
Segment Tree
A range sum query asks for the total of all elements between two indices. Time: O(log n). Space: O(log n) recursion.
Big-O: Build O(n); range query and point update O(log n).
Segment Tree: Range Sum
Segment TreeA range sum query asks for the total of all elements between two indices. Instead of adding every element one by one, the segment tree combines only the handful of pre-computed node values that exactly cover the requested range, skipping over nodes that fall entirely outside it and splitting further only where a node partially overlaps.
How Range Sum Works
- Start at the root, comparing the node's range to the query range.
- If the node's range falls completely outside the query range, contribute nothing and stop this branch.
- If the node's range falls completely inside the query range, return its stored value directly.
- If the node's range partially overlaps, recurse into both children and combine their results.
Range Sum Worked Example
Input: Query sum of range [1,2] over tree built on [2, 4, 6, 8]
- Root covers [0,3], partially overlaps [1,2] → recurse into both children
- Left child covers [0,1], partially overlaps → recurse: index 1's leaf (4) is fully inside, index 0 (2) is outside
- Right child covers [2,3], partially overlaps → recurse: index 2's leaf (6) is fully inside, index 3 (8) is outside
- Combine the fully-inside pieces: 4 + 6 = 10
Output: 10
Press ▶ Run to watch it step by step.
def range_sum(tree, n, l, r):
res = 0
l += n
r += n
while l <= r:
if l % 2 == 1:
res += tree[l] # l is a right child
l += 1
if r % 2 == 0:
res += tree[r] # r is a left child
r -= 1
l //= 2
r //= 2
return res
# O(log n)
# example: range sum on [2, 4, 6, 8]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Range Sum Time & Space Complexity
When to Use Range Sum
- Answering 'total sales between day X and day Y' instantly on changing data
- Range-based analytics dashboards that update live
- Competitive programming problems requiring many range queries mixed with updates
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.