Data Structures · Visualization
Interval Tree: Overlap Query
Interval Tree
Two ranges overlap when each starts before the other ends: low1 ≤ high2 AND low2 ≤ high1. Time: O(log n + k) for k reported overlaps. Space: O(1) extra.
Big-O: Insert O(log n); overlap query O(log n + k).
Interval Tree: Overlap Query
Interval TreeTwo ranges overlap when each starts before the other ends: low1 ≤ high2 AND low2 ≤ high1. The search checks the current node, then uses maxHigh to decide which children could possibly overlap — a child whose subtree ends before the query starts is skipped entirely, which is where the speed comes from.
How Overlap Query Works
- If the current interval overlaps the query, collect it.
- If the left child exists and left.maxHigh ≥ query.low, search left.
- Otherwise (or additionally, when intervals can span), search right.
- Repeat until pruned branches stop the walk — each reported overlap costs O(1).
Overlap Query Worked Example
Input: Query [4, 7] against [1, 3], [5, 8], [2, 6], [9, 12]
- [2, 6] vs [4, 7]: 2 ≤ 7 and 4 ≤ 6 → overlap, collect.
- Left maxHigh 3 < 4 → skip the whole left branch.
- [5, 8] vs [4, 7] → overlap, collect.
- [9, 12]: 9 > 7 → no overlap, stop.
Output: 2 overlaps found, 1 branch pruned, 1 interval rejected
Press ▶ Run to watch it step by step.
def overlaps(a, b):
return a[0] <= b[1] and b[0] <= a[1]
def query(node, q, out):
if not node: return
if overlaps(node['iv'], q): out.append(node['iv'])
if node.get('left') and node['left']['max'] >= q[0]:
query(node['left'], q, out) # left may overlap
# else: whole branch pruned
if node.get('right') and node['iv'][0] <= q[1]:
query(node['right'], q, out) # O(log n + k)
# example: queryBehind 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.
Overlap Query Time & Space Complexity
When to Use Overlap Query
- 'What meetings clash with 2–4pm?' in scheduling UIs
- Collision broad-phase: which objects touch this region?
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.