1. Understand the Goal: The user wants a program that implements an Interval Tree.
-
What is an Interval Tree?
- It's a data structure used to hold intervals (e.g., [start, end]).
- It allows for efficient querying of intervals that overlap with a given point or another interval.
- Typically implemented as an augmented Self-Balancing Binary Search Tree (like a Red-Black Tree or AVL Tree) or a simple Binary Search Tree (BST) where nodes store the maximum endpoint of the subtree.
- Key operations: Insert, Search (overlap query).
-
Determine the Language: Python is generally the most accessible and readable language for algorithmic implementations unless specified otherwise. I'll use Python.
-
Design the Data Structure:
- Node: Needs to store:
interval: A tuple or object (start, end).
left, right: Child pointers.
max_end: The maximum end value found in the subtree rooted at this node. This is crucial for the augmentation.
- Tree: Needs a
root.
-
Core Algorithms:
-
Insertion:
- Standard BST insertion based on
start time.
- Update: After every recursive step, update the
max_end of the current node.
- Self-balancing? For a basic implementation, a simple BST is often sufficient to demonstrate the concept. If I implement a Red-Black tree, the code gets very long and complex. I will stick to a standard BST but mention that real-world implementations usually use self-balancing trees to avoid O(n) worst-case time. Self-correction: Actually, even a simple BST implementation needs to handle the
max update correctly.
-
Search (Overlap with a Point or Interval):
- To find all overlaps, we need to traverse.
- Pruning logic (the magic of the
max_end augmentation):
- If we go left:
- If
left_child exists AND left_child.max_end >= query_start, then there might be an overlap in the left subtree.
- If we go right:
- If
node.interval.start <= query_end (standard BST logic for interval search) AND right_child exists.
-
Simplification: Let's implement a search that returns one overlapping interval, or a function that returns all overlapping intervals. Returning all is usually what people want.
-
Step-by-Step Implementation Plan (Python):
- Class
Interval: Helper class to make tuple handling cleaner.
- Class
Node: Stores interval, left, right, max.
- Class
IntervalTree:
insert(interval): Recursive helper needed.
search(point) or search(interval): Recursive helper needed.
-
Refining the Insertion Logic:
- Compare
interval.start with node.interval.start.
- If
interval.start < node.interval.start: go left.
- Else: go right.
- Crucial Step: After insertion,
node.max = max(node.interval.end, node.left.max if left else -inf, node.right.max if right else -inf).
-
Refining the Search Logic (Finding all overlapping intervals):
- Function
search_all(query_interval)
- Base case: If node is None, return.
- Check overlap logic:
(start1 <= end2) and (start2 <= end1).
- If overlap: Add to results.
- Decide where to recurse:
- If
node.left is not None and node.left.max >= query.start: Recurse left. (This is the pruning optimization).
- If
node.right is not None and node.interval.start <= query.end: Recurse right.
-
Drafting the Code (Mental or Scratchpad):
class Node:
def __init__(self, interval):
self.interval = interval
self.max = interval.end
self.left = None
self.right = None
def insert(root, interval):
if root is None: return Node(interval)
if interval.start < root.interval.start:
root.left = insert(root.left, interval)
else:
root.right = insert(root.right, interval)
# Update max
root.max = max(root.max, interval.end)
return root
-
Handling Complexity/Edge Cases:
- Empty tree.
- Duplicate intervals.
- Non-overlapping intervals.
-
Writing the Solution:
- I will write a complete Python script.
- It will include a
Interval class (or just use tuples for simplicity? A class is nicer for dot notation like i.low).
- It will include
IntervalTree class.
- I will add a
main block to demonstrate usage (insert some intervals, search for overlaps).
-
Reviewing the Search Logic (Self-Correction):
- The standard interval tree search is usually for any overlap.
- Algorithm:
- If
root is None, return.
- If
root.interval overlaps query, add to list.
- If
root.left is not None and root.left.max >= query.low:
recurse left.
- Recurse right (condition helps optimize but technically you usually check right if left doesn't satisfy or if you need all matches).
- Actually, for finding all matches:
- Check left: Only if
left.max >= query.start.
- Check right: Only if
right.max >= query.start AND node.start <= query.end (Wait, no).
- Standard traversal logic:
- Go left if potential overlap exists (
left.max >= query.start).
- Go right if potential overlap exists.
- Because it's a BST based on
start times:
- If
node.start > query.end: We must go left, we cannot go right.
- If
node.start <= query.end: We might go right.
- Let's stick to the robust recursive logic used in CLRS (Introduction to Algorithms):
- Go left if
left != null and left.max >= low.
- Check current node.
- Go right if
right != null and node.start <= high.
-
Final Code Structure:
- Class
Node.
- Class
IntervalTree.
- Methods:
add, remove (maybe too complex for a demo? I'll skip delete to keep it concise unless essential), search (find all overlaps).
- Demonstration.
-
Refining the implementation details:
- I'll use tuples
(low, high) for intervals to keep the code clean, but wrap them in the Node.
- I will implement a helper
do_overlap function.
-
Output Generation: (Produce the Python code based on these thoughts). I will add comments explaining the max_end logic since that's the core of the Interval Tree concept.
(Self-Correction during drafting): The prompt just asks for "a program". I should make it a CLI tool or a script with a clear main function. A simple class definition + test case is best.
- Language Choice: Python is best for readability.
- Balancing: I will implement a standard BST. I will add a note that for guaranteed O(logn), a Red-Black or AVL tree is needed, but the logic remains the same (augmenting with
max).
Let's write the code.
- Define
Node with low, high, max, left, right.
insert(node, low, high)
search(node, low, high) -> returns list of overlapping intervals.
overlap_check(i1, i2) utility.
Search logic detail:
To find all intervals overlapping (low, high):
def search(node, low, high, result):
if not node: return
# If left child exists and its max is >= search low, go left
if node.left and node.left.max >= low:
search(node.left, low, high, result)
# Check current node
if do_overlap((node.low, node.high), (low, high)):
result.append((node.low, node.high))
# If right child exists and its start is <= search high, go right?
# Actually, simpler logic:
# We organize by 'low'.
# If node.low > high: No need to look right (since all right are even higher). Must look left.
# If node.low <= high: We might look right.
# But generally, for "find all", we explore branches that *could* contain overlaps.
# Branch conditions:
# Left: if left.max >= low.
# Right: if node.low <= high.
if node.right and node.low <= high: # Optimization: only go right if current start is before query end
search(node.right, low, high, result)
Actually, checking the standard implementation again.
If left is not null and left.max >= low: recurse left.
If right is not null and right.max >= low AND node.low <= high: recurse right? No, that's too specific.
Let's stick to the standard property:
Any interval [a, b] in the left subtree satisfies a <= node.a.
Any interval [a, b] in the right subtree satisfies a >= node.a.
Query [q_low, q_high].
-
Check current node.
-
If left != null and left.max >= q_low:
Recurse left. (Reason: Left subtree might contain intervals extending far enough to reach q_low).
-
If right != null and right.max >= q_low and node.a <= q_high?
No, simply:
If node.a < q_high: Recurse right?
Actually, for a simple BST, the safest way to find all is:
Recurse Left if promising.
Recurse Right if promising.
Promising Left: left.max >= q_low.
Promising Right: right is not null AND node.a <= q_high. (If node.a > q_high, then everything in right subtree has start >= node.a > q_high, so they cannot overlap q_high).
Okay, ready.
Here is a complete implementation of an Interval Tree in Python.
An Interval Tree is a data structure used to hold intervals. In this implementation, we use a self-balancing Augmented Binary Search Tree (specifically an AVL tree structure) to ensure operations remain efficient (O(logN)).
The Concept
- Structure: It is a Binary Search Tree where the key is the start (low point) of the interval.
- Augmentation: Every node stores an extra piece of data:
max_end. This value represents the maximum end (high point) found in the subtree rooted at that node.
- Search Optimization: The
max_end allows us to prune the search. If we are looking for an overlap and the left child's max_end is less than the start of our query interval, we know instantly that no interval in the left subtree can possibly overlap, so we skip it.
Python Implementation
class Interval:
def __init__(self, low, high):
if low > high:
raise ValueError("Low cannot be greater than high")
self.low = low
self.high = high
def __str__(self):
return f"[{self.low}, {self.high}]"
def overlaps(self, other):
"""Checks if this interval overlaps with another interval."""
return self.low <= other.high and other.low <= self.high
class Node:
def __init__(self, interval):
self.interval = interval
self.left = None
self.right = None
self.height = 1 # Needed for AVL balancing
self.max_end = interval.high # The augmentation attribute
class IntervalTree:
def __init__(self):
self.root = None
# ------------------ Public Methods ------------------
def insert(self, low, high):
"""Public method to insert an interval."""
interval = Interval(low, high)
self.root = self._insert(self.root, interval)
def find_overlaps(self, low, high):
"""Public method to find all intervals overlapping with [low, high]."""
query = Interval(low, high)
results = []
self._find_overlaps(self.root, query, results)
return results
def inorder(self):
"""Public method to print tree (for debugging/visualization)."""
return self._inorder(self.root)
# ------------------ Private Helpers ------------------
def _get_height(self, node):
if not node:
return 0
return node.height
def _get_max(self, node):
if not node:
return float('-inf')
return node.max_end
def _update_node(self, node):
"""Updates height and max_end of the node."""
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
# The max_end is the maximum of:
# 1. The node's own high value
# 2. The max_end of the left child
# 3. The max_end of the right child
node.max_end = max(node.interval.high,
self._get_max(node.left),
self._get_max(node.right))
def _get_balance(self, node):
if not node:
return 0
return self._get_height(node.left) - self._get_height(node.right)
def _rotate_right(self, y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
# Update heights and max values (y first, then x)
self._update_node(y)
self._update_node(x)
return x
def _rotate_left(self, x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
self._update_node(x)
self._update_node(y)
return y
def _insert(self, node, interval):
# 1. Standard BST Insert (keyed by interval.low)
if not node:
return Node(interval)
if interval.low < node.interval.low:
node.left = self._insert(node.left, interval)
else:
node.right = self._insert(node.right, interval)
# 2. Update height and max_end of current node
self._update_node(node)
# 3. Get balance factor
balance = self._get_balance(node)
# 4. Balance the tree (AVL Rotations)
# Left Left Case
if balance > 1 and interval.low < node.left.interval.low:
return self._rotate_right(node)
# Right Right Case
if balance < -1 and interval.low >= node.right.interval.low:
return self._rotate_left(node)
# Left Right Case
if balance > 1 and interval.low >= node.left.interval.low:
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
# Right Left Case
if balance < -1 and interval.low < node.right.interval.low:
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
return node
def _find_overlaps(self, node, query, results):
if not node:
return
# If the query interval overlaps with the current node
if node.interval.overlaps(query):
results.append(node.interval)
# Optimization Logic using max_end:
# If the left child exists and its max_end is >= query.low,
# there MIGHT be an overlap in the left subtree.
# (Because something in the left extends far enough to reach the start of our query).
if node.left and node.left.max_end >= query.low:
self._find_overlaps(node.left, query, results)
# Standard BST Search logic based on Low values:
# If the query starts after the current node starts, we must look right.
# If the query starts before the current node starts, we normally look left.
# Note: We might need to explore both children in an interval tree,
# but the max_end check handles the left side pruning.
# We look right if:
# 1. There is a right child.
# 2. The current node's start is less than or equal to the query's end.
# (If node.start > query.end, everything to the right starts after query ends, so no overlap).
if node.right and node.interval.low <= query.high:
self._find_overlaps(node.right, query, results)
def _inorder(self, node):
res = []
if node:
res = self._inorder(node.left)
res.append(f"{node.interval} (MaxEnd: {node.max_end})")
res = res + self._inorder(node.right)
return res
# ------------------ Usage Example ------------------
if __name__ == "__main__":
it = IntervalTree()
print("Inserting intervals: [15,20], [10,30], [17,19], [5,20], [12,15], [30,40]")
# Inserting data
it.insert(15, 20)
it.insert(10, 30)
it.insert(17, 19)
it.insert(5, 20)
it.insert(12, 15)
it.insert(30, 40)
# Visualize Tree Structure (In-order traversal)
# This shows the tree is sorted by 'low' value
print("\nTree Structure (In-order):")
for item in it.inorder():
print(item)
# Search for overlaps
query_range = (14, 16)
print(f"\nSearching for intervals overlapping with {query_range}...")
overlaps = it.find_overlaps(*query_range)
if overlaps:
print("Found overlaps:")
for interval in overlaps:
print(f" - {interval}")
else:
print("No overlaps found.")
# Search for a non-overlapping range
query_range_2 = (25, 28)
print(f"\nSearching for intervals overlapping with {query_range_2}...")
overlaps_2 = it.find_overlaps(*query_range_2)
if overlaps_2:
print("Found overlaps:")
for interval in overlaps_2:
print(f" - {interval}")
else:
print("No overlaps found.")
How it works
-
Insertion:
- The tree is sorted based on the
low value of the intervals (Standard BST property).
- During insertion, we also update the
max_end attribute. This value keeps track of the maximum high value present in that subtree.
- We use AVL rotations to keep the tree balanced. This ensures that the tree depth remains O(logN), preventing worst-case scenarios where the tree becomes a straight line.
-
Searching:
- When we search for an interval (e.g.,
[14, 16]), we traverse the tree.
- Pruning (The "Interval Tree" magic):
- Normally in a BST, if the target is smaller than the current node, you go left.
- In an Interval Tree, we check
if node.left.max_end < query.low. If the maximum endpoint in the left subtree doesn't even reach the start of our query, we know no interval in the left subtree can possibly overlap. We can skip the entire left branch.
- This pruning makes searching significantly faster than iterating through a list.