Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Segment Tree Implementation in Java

19 min readadvanced
Website QA and SEO audits

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

A segment tree answers range queries over an array, sum, minimum, maximum, greatest common divisor, in O(log n), and it also supports updating a single element in O(log n). That combination is what distinguishes it from a prefix-sum array, which answers range sums in O(1) but needs O(n) to absorb an update. The structure is a complete binary tree stored in a flat array of size 2n or 4n, where each node holds the merge of its two children and the root holds the merge of everything. Any associative merge works, which is why one implementation serves sum, min, max and gcd by swapping a single function. The topic looks entirely language-neutral, and it is the one place where that assumption is most expensive: the merge is usually addition, and the eight languages below disagree profoundly about what happens when an addition overflows.

Segment Tree in Java: what you actually reach for

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.

Java implementation

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. Keep the tree in a primitive array rather than an Integer[], and make the merge a private static method so the JIT can inline it rather than dispatching through a functional interface.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(log n)

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. The asymptotic cost is the same in every language, O(log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Segment Tree between languages.

Real-World Applications

Segment Tree applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Segment Tree helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Segment Tree appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Segment Tree over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Segment Tree to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.