DEV Community

Cover image for Interval Intersection in 15 Seconds
Crack Tech
Crack Tech

Posted on

Interval Intersection in 15 Seconds

Interval Intersection gets simple once both lists are sorted by start.

Use two pointers, one in each list. For the current pair:

  • lo = max(a.start, b.start)
  • hi = min(a.end, b.end)
  • Keep [lo, hi] only if lo <= hi.
  • Move the interval that ends first, because it cannot overlap anything later.
a.sort()
b.sort()

i = j = 0
ans = []
while i < len(a) and j < len(b):
    lo = max(a[i][0], b[j][0])
    hi = min(a[i][1], b[j][1])
    if lo <= hi:
        ans.append([lo, hi])
    if a[i][1] < b[j][1]:
        i += 1
    else:
        j += 1
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(m log m + n log n) — sorting is the cost; the pass is O(m + n).

Video: https://youtube.com/shorts/8brhjWGeC9k

Question for you: why move the interval that ends first, not the one that starts first?

Follow Crack Tech for Day 3: Line Sweep.

Mentorship: https://cracktech.app

Top comments (0)