Javascript Solution using sort and Reduce


  • 0
    R

    Feedback always appreciated! O(n) time complexity with O(n) space worst case.

    const merge = function(intervals, res = []) {
        if (intervals.length <= 1) {
          return intervals;
        }
      
        if (!Array.isArray(intervals) && typeof intervals.length[0] !== "object") {
          return false;
        }
        
        intervals.sort((item1, item2) => {
           return item1.start - item2.start; 
        });
        
        intervals.reduce((item1, item2, index) => {
          let last = res[res.length -1];
    
          if (item2.start <= item1.end && item2.end >= item1.start) {
            last.end < item2.end ? last.end = item2.end : last.end = last.end;
            last.start > item2.start ? last.start = item2.start : last.start = last.start;
            return last;
          } else {
            res.push(item2);
            return item2;
          }
          
        }, []);
      
        return res;
      
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.