AdvancedAbout 45 min

    Segment Tree

    Read the full article on Substack

    7 min read.

    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.

    Think of it this way: 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.

    array201152334475

    Build a sum tree over 6 values; each node stores the sum of a range.

    1/36

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    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

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

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

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going