Segment Tree Implementation in Java
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 Java as in every other language.
- ✓An int[] or long[] for storage; the JDK has no segment tree. The important standard-library facts here are Math.addExact, which throws ArithmeticException on overflow, and the fact that long gives you 63 bits of headroom for essentially free.
- ✓Use long[] for any sum tree unless you have proven the values cannot exceed int range, the memory cost is trivial next to the class of bug it removes.
- ✓The Java trap: int arithmetic overflows silently, wrapping to negative, and this is the classic segment tree bug in Java: a tree built over int values whose SUM exceeds 2^31-1 returns a negative total for large ranges while every small test passes.
- ✓A long[] is contiguous and the query loop is tight, so the JIT compiles this to close to C performance after warm-up.
What Segment Tree actually is
Segment Tree in Java: what you actually reach for
Java implementation
public final class SegmentTree {
private final int n;
private final long[] tree; // long, not int: int sums overflow silently
public SegmentTree(long[] data) {
this.n = data.length;
this.tree = new long[2 * n];
System.arraycopy(data, 0, tree, n, n);
for (int i = n - 1; i > 0; i--) {
tree[i] = merge(tree[2 * i], tree[2 * i + 1]);
}
}
// Math.addExact THROWS on overflow instead of wrapping to negative.
private static long merge(long a, long b) {
return Math.addExact(a, b);
}
public void update(int index, long value) {
int i = index + n;
tree[i] = value;
while (i > 1) {
i >>= 1;
tree[i] = merge(tree[2 * i], tree[2 * i + 1]);
}
}
/** Merge of [left, right). */
public long query(int left, int right) {
long acc = 0L;
int lo = left + n;
int hi = right + n;
while (lo < hi) {
if ((lo & 1) == 1) acc = merge(acc, tree[lo++]);
if ((hi & 1) == 1) acc = merge(acc, tree[--hi]);
lo >>= 1;
hi >>= 1;
}
return acc;
}
// Midpoints elsewhere: lo + (hi - lo) / 2, never (lo + hi) / 2.
}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 Java-specific trap
Performance in Java, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Segment Tree?
An int[] or long[] for storage; the JDK has no segment tree. The important standard-library facts here are Math.addExact, which throws ArithmeticException on overflow, and the fact that long gives you 63 bits of headroom for essentially free.
What is the most common Java mistake when implementing Segment Tree?
int arithmetic overflows silently, wrapping to negative, and this is the classic segment tree bug in Java: a tree built over int values whose SUM exceeds 2^31-1 returns a negative total for large ranges while every small test passes. Math.addExact turns that silent corruption into an exception, which is almost always what you want during development. The related trap is computing a midpoint as (lo + hi) / 2, which overflows for large indices, use lo + (hi - lo) / 2.
How does Segment Tree actually perform in Java?
A long[] is contiguous and the query loop is tight, so the JIT compiles this to close to C performance after warm-up. Using Integer[] or a generic implementation with boxed types costs an allocation per element and destroys locality, typically a five-to-tenfold slowdown. Passing the merge as an IntBinaryOperator prevents inlining unless the call site is monomorphic, so a hot tree should hard-code its operation. 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 trialMost AI and dev tools have a student plan. See which ones and how to claim them 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.