DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Merge Intervals

Merge Intervals

Tc : O(nlogn) for sorting the intervals based on start time + O(n) for traversing the intervals
Sc: O(n) for using list + O(n) for using result array

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a,b)->a[0]-b[0]);
        int start = intervals[0][0];
        int end = intervals[0][1];
        List<int[]> list = new ArrayList<>();
        for(int i =1;i<intervals.length;i++){
            if(end >= intervals[i][0]){
                start = Integer.min(intervals[i][0],start);
                end = Integer.max(intervals[i][1],end);
            }
            else{
                list.add(new int[]{start,end});
                start = intervals[i][0];
                end = intervals[i][1];
            }
        }
        list.add(new int[]{start,end});
        int result[][] = new int[list.size()][2];
        for(int i=0;i<list.size();i++){
            result[i] = list.get(i);
        }
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)