← All Exercises

Segment Tree Range Sum

advancedjavascript~40min

Background

Segment trees are used in competitive programming for range queries and in databases for aggregate computations.

Problem

Implement a SegmentTree class that supports range sum queries and point updates, both in O(log n) time complexity.

Input

An array of numbers to initialize the segment tree.

Output

A SegmentTree instance with update(index, value) and queryRange(left, right) methods.

Sample tests

Sample 1

Input: [1,3,5,7,9], queryRange(1,3)
Expected: 15

Your solution

Learning objective

Understand tree-based range query structures and recursive tree construction.