Segment Tree Implementation in Go
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 Go as in every other language.
- ✓A slice for storage; no tree type in the standard library. Since Go 1.18 generics let one implementation serve any merge, and the constraints live in golang.org/x/exp/constraints or a locally declared interface.
- ✓Declare a small type parameter constraint for the element and pass the merge as a func(T, T) T field.
- ✓The Go trap: Go integer overflow wraps silently, with no panic in any build mode and no checked-arithmetic helpers in the standard library.
- ✓A generic Go function is compiled with GC shape stenciling, meaning one instantiation is shared by all pointer-shaped type arguments and dispatches through a dictionary, so a generic segment tree over a pointer type is slower than the equivalent monomorphic code, while one over int64 gets its own specialised instantiation and is fast.
What Segment Tree actually is
Segment Tree in Go: what you actually reach for
Go implementation
package segtree
type Number interface {
~int | ~int64 | ~float64
}
type Tree[T Number] struct {
n int
tree []T
merge func(T, T) T
zero T
}
func New[T Number](data []T, merge func(T, T) T, zero T) *Tree[T] {
n := len(data)
tree := make([]T, 2*n)
copy(tree[n:], data)
for i := n - 1; i > 0; i-- {
tree[i] = merge(tree[2*i], tree[2*i+1])
}
return &Tree[T]{n: n, tree: tree, merge: merge, zero: zero}
}
func (t *Tree[T]) Update(index int, value T) {
i := index + t.n
t.tree[i] = value
for i > 1 {
i /= 2
t.tree[i] = t.merge(t.tree[2*i], t.tree[2*i+1])
}
}
// Query returns the merge of [left, right).
func (t *Tree[T]) Query(left, right int) T {
acc := t.zero
lo, hi := left+t.n, right+t.n
for lo < hi {
if lo&1 == 1 {
acc = t.merge(acc, t.tree[lo])
lo++
}
if hi&1 == 1 {
hi--
acc = t.merge(acc, t.tree[hi])
}
lo /= 2
hi /= 2
}
return acc
}
// Overflow WRAPS silently in every build mode, no panic, no trap.
// Use int64 headroom, or math/bits.Add64 when you must detect it.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 Go-specific trap
Performance in Go, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Segment Tree?
A slice for storage; no tree type in the standard library. Since Go 1.18 generics let one implementation serve any merge, and the constraints live in golang.org/x/exp/constraints or a locally declared interface. Go's int is 64-bit on all mainstream platforms, which gives sum trees comfortable headroom.
What is the most common Go mistake when implementing Segment Tree?
Go integer overflow wraps silently, with no panic in any build mode and no checked-arithmetic helpers in the standard library. Unlike Rust there is no debug build to catch it and unlike Swift there is no trap; unlike Python it is not impossible. So a sum tree over large int32 values converted carelessly, or any accumulation past 2^63, produces a wrong total that nothing reports. The math/bits package has Add64 with a carry output if you need to detect it.
How does Segment Tree actually perform in Go?
A generic Go function is compiled with GC shape stenciling, meaning one instantiation is shared by all pointer-shaped type arguments and dispatches through a dictionary, so a generic segment tree over a pointer type is slower than the equivalent monomorphic code, while one over int64 gets its own specialised instantiation and is fast. Passing merge as a func field is an indirect call the compiler cannot inline; hard-coding addition is measurably quicker in a hot loop. 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 trialBefore paying for GitHub Copilot, check its student and free-tier options 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.