Merge Overlapping Intervals

Given a collection of intervals, merge all overlapping intervals.

For example:

Given [1,3],[2,6],[8,10],[15,18],

return [1,6],[8,10],[15,18].

Make sure the returned intervals are sorted.

public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        Collections.sort(intervals, (a, b) -> a.start - b.start);
        ArrayList<Interval> ans = new ArrayList<>();
        for (int i = 0; i < intervals.size(); i++) {
            Interval t = intervals.get(i);
            while ((i + 1) < intervals.size() && t.end >= intervals.get(i + 1).start) {
                t.end = Math.max(intervals.get(i + 1).end, t.end);
                i++;
            }
            ans.add(t);
        }
        return ans;
    }
}

Last updated