How to Find Intersection of Two Sorted Interval Lists in Python
A two-pointer algorithm that finds all overlapping intervals between two sorted lists of intervals.
Python code
29 linesdef interval_intersection(list1, list2):
i = j = 0
result = []
while i < len(list1) and j < len(list2):
# Find the overlap between current intervals
lo = max(list1[i][0], list2[j][0])
hi = min(list1[i][1], list2[j][1])
# If there's an overlap, add it to result
if lo <= hi:
result.append([lo, hi])
# Move pointer of the interval that ends first
if list1[i][1] < list2[j][1]:
i += 1
else:
j += 1
return result
if __name__ == "__main__":
# Example: two sorted lists of intervals
first = [[0, 2], [5, 10], [13, 23], [24, 25]]
second = [[1, 5], [8, 12], [15, 24], [25, 26]]
intersections = interval_intersection(first, second)
print(intersections)
Output
[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]
How it works
The algorithm uses two pointers i and j to traverse both sorted lists simultaneously. For each pair, it computes the overlap by taking the max of start points and min of end points. If the computed lo is less than or equal to hi, the interval [lo, hi] represents an intersection. Since intervals are sorted, only the interval that ends earlier can have no more overlaps with the current other interval, so we advance that pointer. This gives O(n + m) time complexity — efficient for large lists of intervals.
Common mistakes
- Forgetting to check lo <= hi, which would add empty intervals
- Advancing both pointers instead of only the one ending first
- Assuming intervals are inclusive vs exclusive without checking problem constraints
Variations
- Use a while loop with explicit bounds checks for readability
- Handle edge cases with lists that have no overlaps by returning an empty list
Real-world use cases
- Merging meeting calendars to find common free slots between colleagues.
- Finding overlapping availability windows when scheduling resources or services.
- Computing common coverage regions from camera or sensor range data in mapping systems.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.