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.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
6 vector<vector<int>> result;
7 int i = 0, j = 0;
8 while (i < A.size() && j < B.size()) {
9 int start = max(A[i][0], B[j][0]);
10 int end = min(A[i][1], B[j][1]);
11 if (start <= end) {
12 result.push_back({ start, end });
13 }
14 if (A[i][1] < B[j][1])
15 i++;
16 else
17 j++;
18 }
19 return result;
20}
The approach utilizes two pointers i
and j
to traverse both lists. At each step, find the intersection, if any, and record it. Then advance the pointer with the smaller end time until both lists are fully traversed.