56. Merge Intervals
Level
LeetCode Medium
Recruitment
var merge = function (intervals) {
  if (!intervals.length) {
    return [];
  }

  let front = 1;

  let ans = [];
  let current = 0;

  const sorted = intervals.sort((a, b) => a[0] - b[0]);

  ans.push(sorted[current]);
  current++;

  while (current < sorted.length) {
    const before = ans.pop();
    const after = sorted[current];

    const [f1, e1] = before;
    const [f2, e2] = after;

    if (e1 < f2) {
      // f1 e1 f2 e2
      ans.push(before);
      ans.push(after);
      current++;
      continue;
    }
    if (e2 < f1) {
      ans.push(after);
      ans.push(before);
      current++;
      continue;
    }

    const merged = [];
    if (f1 < f2) {
      merged.push(f1);
      merged.push(Math.max(e1, e2));
    } else {
      merged.push(f2);
      merged.push(Math.max(e1, e2));
    }

    ans.push(merged);
    current++;
  }

  return ans;
};