Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

 

 

Solution:

Sorting the input intervals by each first element.

Traversing the sorted intervals, follow the merge rule to merge.

Merge rule:

if (this.end) <= (next.start),

the new interval should be [this.start, max(this.end, next.end)].

class Solution {
    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) {
            return intervals;
        }
        
        Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));
        
        List<int[]> res = new ArrayList<>();
        int[] newInterval = intervals[0];
        res.add(newInterval);
        
        for (int[] i : intervals) {
            if (newInterval[1] >= i[0]) {
                newInterval[1] = Math.max(newInterval[1], i[1]);
            } else {
                newInterval = i;
                res.add(newInterval);
            }
        }
        
        return res.toArray(new int[res.size()][2]);
    }
}

Time complexity: O(n log(n)), because of the sorting action.

Space complexity: O(1).

Leave a comment