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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

29 lines
Python 3.9+
def 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

stdout
[[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

  1. Use a while loop with explicit bounds checks for readability
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.