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 __repr__(self):
return f"[{self.low}, {self.high}]"
def overlaps(self, other):
"""Checks if two intervals overlap."""
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
# The 'max_end' stores the maximum 'high' value of any interval
# in the subtree rooted at this node.
self.max_end = interval.high
class IntervalTree:
def __init__(self):
self.root = None
def insert(self, low, high):
"""Public method to insert an interval."""
interval = Interval(low, high)
self.root = self._insert_rec(self.root, interval)
def _insert_rec(self, root, interval):
"""Recursive helper to insert an interval based on 'low' value."""
if root is None:
return Node(interval)
# Standard BST insertion logic based on the 'low' value
if interval.low < root.interval.low:
root.left = self._insert_rec(root.left, interval)
else:
root.right = self._insert_rec(root.right, interval)
# Update the max_end value for this ancestor node
# It is the max of the node's own high, and the max_end of its children
root.max_end = max(root.interval.high, root.max_end)
# Note: If we were building a balanced tree (like an AVL),
# we would handle rotations here and update max_end accordingly.
return root
def search_overlaps(self, low, high):
"""Public method to find all intervals overlapping [low, high]."""
query = Interval(low, high)
results = []
self._search_rec(self.root, query, results)
return results
def _search_rec(self, root, query, results):
"""Recursive helper to find overlapping intervals."""
if root is None:
return
# Check if the current node overlaps with the query
if root.interval.overlaps(query):
results.append(root.interval)
# OPTIMIZATION STEP:
# If the left child exists and its 'max_end' is greater than or equal
# to the query's 'low' value, there *might* be an overlap in the left subtree.
# We must check left if: root.left.max >= query.low
go_left = False
if root.left is not None:
if root.left.max_end >= query.low:
go_left = True
if go_left:
self._search_rec(root.left, query, results)
# Logic for going Right:
# 1. If we didn't go left (optimization doesn't apply perfectly to skipping right,
# but standard BST logic applies).
# 2. Since we organized the tree by 'low' values:
# If root.interval.low <= query.high, there is a chance a node on the right
# starts before the query ends, so we must look there.
# However, a simpler logic for standard interval trees is usually just to check
# the right child if it exists.
# Technically, we can prune the right side if root.interval.low > query.high
# (because everything on right starts even later).
# But usually we just traverse. The 'max_end' check is mostly for pruning the Left side
# (which contains smaller 'low' values that might stretch very far to the right).
# To keep it robust, we check the right side if the right child exists.
# To be strictly efficient:
if root.right is not None:
# We can only prune right if the smallest value in right (root.interval.low)
# is strictly greater than query.high.
# Actually, since we didn't necessarily balance, we just check.
self._search_rec(root.right, query, results)
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
it = IntervalTree()
# Insert some intervals
# Intervals: [15, 20], [10, 30], [17, 19], [5, 20], [12, 15], [30, 40]
print("Inserting: [15,20], [10,30], [17,19], [5,20], [12,15], [30,40]")
it.insert(15, 20)
it.insert(10, 30)
it.insert(17, 19)
it.insert(5, 20)
it.insert(12, 15)
it.insert(30, 40)
# Search for intervals that overlap with [14, 16]
query = (14, 16)
print(f"\nSearching for overlaps with {query}...")
overlaps = it.search_overlaps(query[0], query[1])
print(f"Found {len(overlaps)} overlapping intervals:")
for interval in overlaps:
print(f" {interval}")
# Search for a point interval (e.g., exact moment 20)
query_point = (20, 20)
print(f"\nSearching for overlaps with point {query_point}...")
overlaps = it.search_overlaps(query_point[0], query_point[1])
print(f"Found {len(overlaps)} overlapping intervals:")
for interval in overlaps:
print(f" {interval}")