Categories
interview

Merge Intervals

If  “n” is the length of the input list, then the “Time Complexity”  is O(nlogn).

/**
 * 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; }
 * }
 */

class Solution {
 public List < Interval > merge(List < Interval > intervals) {
  // Sort the input list by the start times.
  Collections.sort(intervals, (a, b) -> a.start - b.start);
  List < Interval > ret = new ArrayList < Interval > ();
  Interval prev = null;
  for (Interval curr: intervals) {
   if (prev == null) {
    prev = curr;
   } else {
    if (curr.start <= prev.end) {
     prev.end = Math.max(curr.end, prev.end);
    } else {
     ret.add(prev);
     prev = curr;
    }
   }
  }
  if (prev != null) {
   ret.add(prev);
  }
  return ret;
 }
}