Merge Intervals in TypeScript

function merge(intervals: number[][]): number[][] {
    // Step 1: Sort the intervals based on their start times.
    intervals.sort((a, b) => a[0] - b[0]);

    // The output array to store merged intervals
    const merged: number[][] = [];

    // Step 2: Iterate through the sorted intervals
    for (const interval of intervals) {
        // If the output array is empty or the current interval does not overlap with the last interval in the output,
        // simply add the interval to the output array.
        if (merged.length === 0 || merged[merged.length - 1][1] < interval[0]) {
            merged.push(interval);
        } else {
            // Step 3: If there is an overlap, merge the current interval with the last interval in the output array
            merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
        }
    }

    // Step 4: Return the merged intervals
    return merged;
}

PrevNext