Interval Intersection List

Similar to this question, I was asked to find the intersection between intervals.

Code to merge interval intersection between 2 lists
https://leetcode.com/problems/interval-list-intersections/discuss/231122/Java-two-pointers-O(m-%2B-n)

public int[][] intervalIntersection(int[][] A, int[][] B) {
    if(A == null || A.length == 0 || B == null || B.length == 0)
        return new int[][]{};
    List<int[]> res = new ArrayList<>();
    
    int i = 0, j = 0;
    int startMax, endMin;
    while(i < A.length && j < B.length){
        startMax = Math.max(A[i][0], B[j][0]);
        endMin = Math.min(A[i][1], B[j][1]);
        
        if(endMin >= startMax)
            res.add(new int[]{startMax, endMin});
        
        if(A[i][1] == endMin) i++;
        if(B[j][1] == endMin) j++;
    }
    
    return res.toArray(new int[res.size()][2]);
}

Is this code correct to just merge for 1 list?

public List<int[]> overlap(List<int[]> a)
    {
        //Sort array by start
        List<int[]>r=new ArrayList<>();

        int startMax, endMin;
        int i=0,j=1;
        while(i < a.size()-1){
            int[] a1 = a.get(i);
            int[] a2 = a.get(i+1);
            startMax = Math.max(a1[0], a2[0]);
            endMin = Math.min(a1[1], a2[1]);

            if(endMin >= startMax)
                r.add(new int[]{startMax, endMin});
            i++;
        }
	return r;
}
Comments (0)