Data Structures · Visualization

Interval Tree: Insert

Interval Tree

Insertion walks down by low endpoint exactly like a BST insert, then repairs maxHigh on the way back up. Time: O(log n) average, O(n) worst case unbalanced. Space: O(1) extra per insert.

Big-O: Insert O(log n); overlap query O(log n + k).

Interval Tree: Insert

Interval Tree

Insertion walks down by low endpoint exactly like a BST insert, then repairs maxHigh on the way back up. Each ancestor's maxHigh becomes the maximum of its own high and both children's maxHigh — one bottom-up pass keeps every future search correctly pruned.

How Insert Works

  1. Compare the new low with the node: go left if smaller, right otherwise.
  2. Insert at the first empty spot, like a plain BST.
  3. Walk back to the root recomputing maxHigh at each ancestor.
  4. maxHigh[node] = max(node.high, maxHigh[left], maxHigh[right]).

Insert Worked Example

Input: Insert [9, 12] into a tree holding [1, 3], [5, 8], [2, 6]

  1. 9 > root low 2 → go right to [5, 8].
  2. 9 > 5 → empty right slot: place [9, 12].
  3. Recompute: maxHigh of [5, 8] becomes 12.
  4. Recompute: root maxHigh becomes 12.

Output: Tree holds 4 intervals; root maxHigh = 12

Interval Tree: Introduction
Ranges with a maxHigh shortcut per subtree for overlap pruning.
[1, 3]
[5, 8]
[2, 6]
Visiting Overlaps query
Interval Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Interval Tree in Code
def insert(root, iv):
    if not root:
        return {'iv': iv, 'max': iv[1]}
    if iv[0] < root['iv'][0]:
        root['left'] = insert(root.get('left'), iv)
    else:
        root['right'] = insert(root.get('right'), iv)
    root['max'] = max(root['iv'][1], ...)  # repair up
    return root
# example: insert
Input: Insert [9, 12] into a tree holding [1, 3], [5, 8], [2, 6]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Insert Time & Space Complexity

TimeO(log n) average, O(n) worst case unbalanced
SpaceO(1) extra per insert

When to Use Insert

  • Live schedulers inserting bookings as users click
  • Windowing systems tracking visible rectangles

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.