Segment Tree for Range Sum Queries
Answer range sum queries and point updates in logarithmic time with an array-backed segment tree and strict bounds validation.
Code
export class SegmentTree {
private readonly size: number;
private readonly tree: number[];
constructor(values: readonly number[]) {
if (!Array.isArray(values)) throw new TypeError("values must be an array");
for (const value of values) {
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError("values must contain finite numbers");
}
}
this.size = values.length;
this.tree = new Array<number>(Math.max(4, this.size * 4)).fill(0);
if (this.size > 0) this.build(values, 1, 0, this.size - 1);
}
sum(left: number, right: number): number {
if (!Number.isInteger(left) || !Number.isInteger(right)) {
throw new TypeError("range bounds must be integers");
}
if (left < 0 || right >= this.size || left > right) throw new RangeError("invalid range");
return this.query(1, 0, this.size - 1, left, right);
}
update(index: number, value: number): void {
if (!Number.isInteger(index) || index < 0 || index >= this.size) {
throw new RangeError("index out of range");
}
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError("value must be a finite number");
}
this.assign(1, 0, this.size - 1, index, value);
}
private build(values: readonly number[], node: number, start: number, end: number): void {
if (start === end) {
this.tree[node] = values[start] ?? 0;
return;
}
const middle = (start + end) >> 1;
this.build(values, node * 2, start, middle);
this.build(values, node * 2 + 1, middle + 1, end);
this.tree[node] = this.tree[node * 2] + this.tree[node * 2 + 1];
}
private query(node: number, start: number, end: number, left: number, right: number): number {
if (left <= start && end <= right) return this.tree[node];
const middle = (start + end) >> 1;
let total = 0;
if (left <= middle) total += this.query(node * 2, start, middle, left, right);
if (right > middle) total += this.query(node * 2 + 1, middle + 1, end, left, right);
return total;
}
private assign(node: number, start: number, end: number, index: number, value: number): void {
if (start === end) {
this.tree[node] = value;
return;
}
const middle = (start + end) >> 1;
if (index <= middle) this.assign(node * 2, start, middle, index, value);
else this.assign(node * 2 + 1, middle + 1, end, index, value);
this.tree[node] = this.tree[node * 2] + this.tree[node * 2 + 1];
}
}
const tree = new SegmentTree([2, 4, 6, 8, 10]);
console.log(tree.sum(1, 3));
tree.update(2, 0);
console.log(tree.sum(0, 4));
console.log(tree.sum(2, 2));Output
Captured from a sandboxed run of this snippet in the build pipeline.
18
24
0What the code does
The code’s whole job belongs to the class SegmentTree and the function middle.
Repetition is confined to for (const value of values) — the rest of the file is straight-line. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
Watch out for
- The guard
left < 0 || right >= this.size || left > rightshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
SegmentTree is the public entry point; everything else in the file exists to support it.
Statements that matter
if (left < 0 || right >= this.size || left > right) throw new RangeError("invalid range");
if (right > middle) total += this.query(node * 2 + 1, middle + 1, end, left, right);
if (left <= middle) total += this.query(node * 2, start, middle, left, right);
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.
FAQ
- What happens on invalid input?
- The code throws `TypeError` and `RangeError` — the guard `left < 0 || right >= this.size || left > right` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `middle` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.