Greedy Algorithms8 sections · 316 units
Open in Course

Interval Intersections - Implementation

The code

function intervalIntersection(A, B)
 result := []
 i := 0
 j := 0
 while i < length of A and j < length of B
 lo := max(A[i].start, B[j].start)
 hi := min(A[i].end, B[j].end)
 if lo <= hi then
 result.append([lo, hi])
 if A[i].end < B[j].end then
 i := i + 1
 else
 j := j + 1
 return result

Time: O(n+m)O(n + m). Space: O(1)O(1) extra.