DEV Community

Cover image for Algorithm of merge overlapping intervals
Davyd NRB
Davyd NRB

Posted on

Algorithm of merge overlapping intervals

Solution for complex js interview questions

const mergeIntersectingRanges = (ranges) =>
  ranges
    .sort((a, b) => a[0] - b[0])
    .reduce(
      (acc, range) => {
        const indexOfLast = acc.length - 1;
        const prevRange = acc[indexOfLast];
        const end = prevRange[1];
        const start = range[0];

        if (end > start) {
          acc[indexOfLast][1] = Math.max(end, range[1]);
        } else {
          acc.push(range);
        }

        return acc;
      },
      [ranges[0]]
    );


mergeIntersectingRanges([[1, 4], [3, 6], [10, 12], [15, 19]]); 
// [[1,6], [10, 12], [15, 19]]


mergeIntersectingRanges([[1, 11], [3, 6], [10, 12], [15, 19]]); 
// [[1,12], [15, 19]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)