986. Interval List Intersections
Asked at 11Meta74Apple30Amazon29Microsoft28Google26Bloomberg8.3Verkada100Yandex67Mixpanel100Nuro60DoorDash53
Problem
Two lists of closed intervals are each sorted and pairwise disjoint. Return their intersection: every range covered by an interval from both lists.
Example: [[0,2],[5,10],[13,23],[24,25]] and [[1,5],[8,12],[15,24],[25,26]] → [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Two pointers over the two sorted lists. Intersection = [max(starts), min(ends)] if non-empty. Advance the list whose interval ends first.
Complexity: O(m + n).
class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
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 res
A = [[0, 2], [5, 10], [13, 23], [24, 25]]
B = [[1, 5], [8, 12], [15, 24], [25, 26]]
assert Solution().intervalIntersection(A, B) == [[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]
assert Solution().intervalIntersection([[1, 3], [5, 9]], []) == []
assert Solution().intervalIntersection([[1, 7]], [[3, 10]]) == [[3, 7]]
class Solution {
public int[][] intervalIntersection(int[][] a, int[][] b) {
List<int[]> res = new ArrayList<>();
int i = 0, j = 0;
while (i < a.length && j < b.length) {
int lo = Math.max(a[i][0], b[j][0]), hi = Math.min(a[i][1], b[j][1]);
if (lo <= hi) res.add(new int[]{lo, hi});
if (a[i][1] < b[j][1]) i++; else j++;
}
return res.toArray(new int[0][]);
}
}
func intervalIntersection(firstList [][]int, secondList [][]int) [][]int {
res := [][]int{}
for i, j := 0, 0; i < len(firstList) && j < len(secondList); {
lo := max(firstList[i][0], secondList[j][0])
hi := min(firstList[i][1], secondList[j][1])
if lo <= hi {
res = append(res, []int{lo, hi})
}
if firstList[i][1] < secondList[j][1] { // the one ending first cannot meet anything else
i++
} else {
j++
}
}
return res
}