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.
1var intervalIntersection = function(firstList, secondList) {
2 let i = 0, j = 0;
3 const result = [];
4 while (i < firstList.length && j < secondList.length) {
5 let start = Math.max(firstList[i][0], secondList[j][0]);
6 let end = Math.min(firstList[i][1], secondList[j][1]);
7 if (start <= end) {
8 result.push([start, end]);
9 }
10 if (firstList[i][1] < secondList[j][1]) {
11 i++;
12 } else {
13 j++;
14 }
15 }
16 return result;
17};
The JavaScript solution applies a similar two-pointer logic. We track current intervals within both lists, check for intersections, and adjust our pointers according to interval end times. Intersections found are added to the result array.