Interval List Intersections
Difficulty: Medium · Pattern: Intervals · LeetCode #986
You're given two lists of closed intervals. Each list is pairwise disjoint and sorted. Return their intersection.
Example
text
A = [[0,2],[5,10],[13,23],[24,25]]
B = [[1,5],[8,12],[15,24],[25,26]]
→ [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]Hints
- Two intervals intersect in
[max(a1,b1), min(a2,b2)]when that range is non-empty. - After comparing, the interval that ends first can't intersect anything else in the other list. Advance it.
Approach
Use two pointers i, j. Compute lo = max(A[i][0], B[j][0]) and hi = min(A[i][1], B[j][1]). If lo ≤ hi, record [lo, hi]. Then advance the pointer whose interval has the smaller end.
O(m + n). It's a merge-like sweep, the same skeleton as Merge Two Sorted Lists.
Complexity
Time: O(m + n). Space: O(1) besides the output.
Python solution
def intervalIntersection(firstList, secondList):
i = j = 0
res = []
while i < len(firstList) and j < len(secondList):
lo = max(firstList[i][0], secondList[j][0])
hi = min(firstList[i][1], secondList[j][1])
if lo <= hi:
res.append([lo, hi])
if firstList[i][1] < secondList[j][1]:
i += 1
else:
j += 1
return resJavaScript solution
function intervalIntersection(firstList, secondList) {
const res = [];
let i = 0, j = 0;
while (i < firstList.length && j < secondList.length) {
const lo = Math.max(firstList[i][0], secondList[j][0]), hi = Math.min(firstList[i][1], secondList[j][1]);
if (lo <= hi) res.push([lo, hi]);
if (firstList[i][1] < secondList[j][1]) i++; else j++;
}
return res;
}