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.
1import java.util.*;
2
3class Solution {
4 public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
5 List<int[]> result = new ArrayList<>();
6 int i = 0, j = 0;
7 while (i < firstList.length && j < secondList.length) {
8 int start = Math.max(firstList[i][0], secondList[j][0]);
9 int end = Math.min(firstList[i][1], secondList[j][1]);
10 if (start <= end) {
11 result.add(new int[]{start, end});
12 }
13 if (firstList[i][1] < secondList[j][1])
14 i++;
15 else
16 j++;
17 }
18 return result.toArray(new int[result.size()][]);
19 }
20}
Using a two-pointer technique, the solution traverses both lists and determines intersections based on the maximum of start points and minimum of end points. Intersections are added to the result list, and the appropriate pointer is advanced based on the interval ending times.