Given two lists of closed intervals, each sorted and disjoint, return their intersection.
Input: A=[[0,2],[5,10],[13,23],[24,25]], B=[[1,5],[8,12],[15,24],[25,26]] → Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Two pointers: at each step compute intersection of current intervals. Advance the pointer of the interval that ends first.
- i=0 pointer for A, j=0 for B.
- Intersection: [max(A[i][0], B[j][0]), min(A[i][1], B[j][1])].
- If lo <= hi, add to result.
- Advance whichever interval ends first (min end pointer).
import java.util.*;
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]);
int 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][]);
}
}
- Time Complexity: O(M+N)
- Space Complexity: O(M+N)