Accepted Javascript solution


  • 0
    R

    Feedback for improvement welcomed :)

    function merge(intervals, merged = []) {
        if (!intervals || !intervals.length) {
            return merged;
        }
    
        intervals = intervals.sort(byStart);
    
        for (let i = 0; i < intervals.length; i++) {
            if (overlaps(merged, intervals[ i ])) {
                let interval = intervals[ i ],
                    lastInterval = merged[ merged.length - 1 ];
    
                lastInterval[ 0 ] = Math.min(lastInterval[ 0 ], interval.start);
                lastInterval[ 1 ] = Math.max(lastInterval[ 1 ], interval.end);
            } else {
                merged.push([ intervals[ i ].start, intervals[ i ].end ]);
            }
        }
    
        return merged;
    }
    
    function overlaps(merged, interval) {
        if (!merged.length) {
            return false;
        }
    
        let lastInterval = merged[ merged.length - 1 ];
    
        return lastInterval[ 1 ] >= interval.start &&
            interval.end >= lastInterval[ 0 ];
    }
    
    function byStart(left, right) {
        return left.start - right.start;
    }
    

Log in to reply
 

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