DSA
    advanced

    Segment Tree

    Segment Tree

    A powerful tree data structure for range queries (sum, min, max) and point/range updates in O(log n). Essential for competitive programming and advanced interview problems.

    ⏱ O(log n)
    💾 O(n)
    Ready
    Input Array
    1
    3
    5
    7
    9
    11
    Segment Tree (range sums)
    ············
    active node query range

    Input: [1, 3, 5, 7, 9, 11]. Building Segment Tree for range sum queries.

    50%
    Live Variables
    n6
    treeSize24

    Answer a range query

    Sort

    A segment tree over 8 elements answers sum(2..5). Sort each node by what the query does with it.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Fully inside — use its sum

    Drop items here

    Partial — recurse into children

    Drop items here

    Outside — ignore

    Drop items here
    7 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What is the key advantage of Segment Tree over Prefix Sum?

    The short version

    Imagine a company hierarchy. To find total sales for a region, the regional manager already has aggregated data from city managers, who have it from store managers. You don't sum every store - you query pre-computed subtotals at just the right level.

    In more depth

    The Power of Preprocessing

    Segment Tree stores a tree of precomputed aggregate values (sum, min, max, etc.) for ranges of the array.

    Structure:

    Leaf nodes = original array elements
    Internal nodes = aggregate of children's values
    Tree height = O(log n)

    Operations:

    Build: O(n) - bottom-up construction
    Query(l, r): O(log n) - combine relevant segments
    Update(i, val): O(log n) - update path from leaf to root

    Lazy Propagation:

    For range updates, defer updates to children until needed. Enables O(log n) range updates instead of O(n).

    Key Gotchas:

    Array size is typically 4*n for safety
    1-indexed vs 0-indexed causes many bugs
    Remember to push lazy updates before queries

    When to reach for this

    • Range queries + range/point updates
    • Need O(log n) for both query and update
    • Interval problems with modifications
    • Count inversions, smaller elements after self

    Interview Questions

    Google
    Amazon
    Google
    Amazon
    Microsoft
    Google
    Uber
    Google
    Amazon
    Facebook

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required