Segment Tree Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Segment Tree runs in O(log n) time and O(n) space, in TypeScript as in every other language.
- ✓The same arrays as JavaScript, with generics letting one implementation serve every merge.
- ✓Take the monoid as a constructor parameter: { merge: (a: T, b: T) => T; identity: T }. That single interface documents the associativity requirement, makes sum, min, max and gcd trees the same class, and gives the identity a home, the query loop needs it as the starting accumulator and hand-written implementations usually hard-code a zero that is wrong for a min tree.
- ✓The TypeScript trap: The type system cannot check associativity, so a merge like subtraction or average type-checks perfectly and produces answers that are wrong only for some ranges, the hardest possible bug to spot, because small tests pass.
- ✓Identical to JavaScript once compiled. The generic version does cost something real: a T[] of a generic type is a boxed array, so it loses the typed-array advantage.
What Segment Tree actually is
Segment Tree in TypeScript: what you actually reach for
TypeScript implementation
export interface Monoid<T> {
readonly merge: (a: T, b: T) => T; // MUST be associative
readonly identity: T; // merge(x, identity) === x
}
export class SegmentTree<T> {
private readonly n: number;
private readonly tree: T[];
constructor(data: readonly T[], private readonly monoid: Monoid<T>) {
this.n = data.length;
this.tree = new Array<T>(2 * this.n).fill(monoid.identity);
for (let i = 0; i < this.n; i++) this.tree[i + this.n] = data[i] as T;
for (let i = this.n - 1; i > 0; i--) {
this.tree[i] = monoid.merge(this.tree[2 * i] as T, this.tree[2 * i + 1] as T);
}
}
update(index: number, value: T): void {
let i = index + this.n;
this.tree[i] = value;
while (i > 1) {
i >>= 1;
this.tree[i] = this.monoid.merge(this.tree[2 * i] as T, this.tree[2 * i + 1] as T);
}
}
query(left: number, right: number): T {
let acc = this.monoid.identity; // NOT a hard-coded 0
let lo = left + this.n;
let hi = right + this.n;
while (lo < hi) {
if (lo & 1) acc = this.monoid.merge(acc, this.tree[lo++] as T);
if (hi & 1) acc = this.monoid.merge(acc, this.tree[--hi] as T);
lo >>= 1;
hi >>= 1;
}
return acc;
}
}
export const sumMonoid: Monoid<number> = { merge: (a, b) => a + b, identity: 0 };
export const minMonoid: Monoid<number> = { merge: Math.min, identity: Infinity };Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Segment Tree?
The same arrays as JavaScript, with generics letting one implementation serve every merge. A segment tree is defined by a monoid, an associative merge plus an identity element, and TypeScript can express exactly that as a two-field object, which makes the requirement explicit rather than folklore.
What is the most common TypeScript mistake when implementing Segment Tree?
The type system cannot check associativity, so a merge like subtraction or average type-checks perfectly and produces answers that are wrong only for some ranges, the hardest possible bug to spot, because small tests pass. The identity is the other silent trap: a min-tree seeded with 0 instead of Infinity returns 0 for every range of positive numbers, and the types are entirely happy.
How does Segment Tree actually perform in TypeScript?
Identical to JavaScript once compiled. The generic version does cost something real: a T[] of a generic type is a boxed array, so it loses the typed-array advantage. When performance matters, specialise a numeric implementation over Float64Array alongside the generic one rather than making the generic one clever. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.