import java.util.*;
/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if (intervals.size() == 0 || intervals.size() == 1)
            return intervals;

        intervals.sort((a, b) -> a.start - b.start);
        ArrayList<Interval> list = new ArrayList<>();
        int left = intervals.get(0).start, right = 0;
        
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals.get(i).start > intervals.get(i - 1).end) {
                right = intervals.get(i - 1).end;
                list.add(new Interval(left, right));
                left = intervals.get(i).start;
            } else {
                intervals.get(i).end = Math.max(intervals.get(i).end, intervals.get(i - 1).end);
            }
            if (i == intervals.size() - 1) {
                right = Math.max(intervals.get(i).end, intervals.get(i - 1).end);
                list.add(new Interval(left, right));
            }
        }
      
        return list;
    }
}