Sponsored
Sponsored
In this approach, we use a two-pointer technique to traverse both lists of intervals simultaneously. We check for intersections between the intervals pointed by our two pointers. If there's an intersection, we record it. We then progress the pointer that points to the interval with the smaller endpoint. This ensures that we consider new overlapping possibilities as the intervals in each list are disjoint and sorted.
Time Complexity: O(n + m), where n and m are the number of intervals in the two lists. This is because we process each interval at most once.
Space Complexity: O(1), apart from the output space, since only a few variables are used.
1def intervalIntersection(firstList, secondList):
2 i, j = 0, 0
3 result = []
4 while i < len(firstList) and j < len(secondList):
5 start = max(firstList[i][0], secondList[j][0])
6 end = min(firstList[i][1], secondList[j][1])
7 if start <= end:
8 result.append([start, end])
9 if firstList[i][1] < secondList[j][1]:
10 i += 1
11 else:
12 j += 1
13 return result
The function iterates through both lists with two indexes, i
and j
. It calculates potential intersections, adds valid intersections to the result, and advances the pointer of the interval with the smaller endpoint to discover new intersections.