JSFiddle - React, Tailwind, and code Playground

by Eugen Sunic

JavaScript

/* const list = [
  [1, 3],
  [2, 6],
  [8, 10],
  [15, 18]
];
 */



var merge = function(intervals) {
  if (intervals.length === 0 || intervals.length === 1) return intervals

  function isOverlap(a, b) {
    const [min1, max1] = a || [];
    const [min2, max2] = b || [];
    if ((max1 >= min2 && max1 <= max2) || (max2 >= min1 && max2 <= max1)) {
      return true;
    }
    return false;
  }

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

  while (i < sorted.length) {
    if (isOverlap(result[result.length - 1], sorted[i])) {
      const refPair = result[result.length - 1][1] = Math.max(sorted[i][1], result[result.length - 1][1])
    } else if (isOverlap(sorted[i], sorted[i + 1])) {
      const [min] = sorted[i];
      const max = Math.max(sorted[i][1], sorted[i + 1][1]);
      result.push([min, max]);
    } else {
      result.push(sorted[i])
    }
    i++;
  }
  return result;
}



console.log(merge([
  [1, 4],
  [4, 5]
]));

console.log(merge([
  [1, 4],
  [5, 6]
]));

console.log(merge([
  [1, 3],
  [2, 6],
  [8, 10],
  [15, 18]
]));

console.log(merge([
  [1, 4],
  [2, 3]
]));

console.log(merge([
  [0, 2],
  [1, 4],
  [3, 5]
]));