Browse curriculum

FAANGPrep Sprint

Merge Intervals (LeetCode 56)

Merge Intervals (LeetCode 56): merge all overlapping intervals.

Problem Understanding

Each intervals[i] is a range [start, end]. Combine every group of overlapping ranges into one range and return the result: a list in which no two ranges overlap and every original range is still covered.

Example:

  • Input: [[1,3],[2,6],[8,10],[15,18]]
  • Output: [[1,6],[8,10],[15,18]]
  • Explanation: [1,3] and [2,6] share the stretch from 2 to 3, so they become the single range [1,6].

Algorithm Strategy

  1. Sort the Intervals: First, sort the intervals based on their start times. This brings potentially overlapping intervals next to each other.
  2. Iterate and Merge: Create a merged list and add the first interval.
  3. Compare: For each subsequent interval, check if it overlaps with the last interval in the merged list (i.e., current.start <= last.end).
  4. Update: If they overlap, update the last interval's end time to max(last.end, current.end). If they don't, simply append the current interval to the merged list.

Interactive Visualization

4 INTERVALS

INPUT

intervals · as given

[1,3]

[2,6]

[8,10]

[15,18]

1

18

merged · 0

1

18

Read

:

Last end

:

Merged

0

merged

Empty

 

Merge 4 intervals

Next

Sort by start: already in order: [[1,3], [2,6], [8,10], [15,18]]

Intervals

Legend & Complexity

The interval being merged, tagged “current”

The last interval in merged, tagged “last”, when it is compared

Already in merged: “appended” or “merged”

The returned intervals

Time

O(n log n)

Space

O(n)

Observe how sorting simplifies the problem to a linear merge process.

Dry Run

Input: [[1,3], [2,6], [8,10], [15,18]]

The code appends when merged is empty or its last interval ends before the current one starts (last end < start); otherwise it extends that last interval.

Step Current last end < start? Action merged
Init - - Sort by start: [[1,3], [2,6], [8,10], [15,18]] []
1 [1,3] merged is empty Append [[1,3]]
2 [2,6] 3 < 2? No: overlap End = max(3, 6) = 6 [[1,6]]
3 [8,10] 6 < 8? Yes Append [[1,6], [8,10]]
4 [15,18] 10 < 15? Yes Append [[1,6], [8,10], [15,18]]

Edge Cases & Common Mistakes

  • Empty Input: Handle [] input gracefully.
  • Single Interval: Don't crash on inputs like [[1,4]].
  • Completely Contained: [[1,10], [2,5]] -> Merge logic max(10, 5) = 10 handles this.
  • Touching: [[1,2], [2,3]] -> 2 <= 2, so they merge into [1,3].

Solution

Optimal solution using O(N log N) sorting.

Merge Intervals Code
1var merge = function(intervals) {
2 intervals.sort((a, b) => a[0] - b[0]);
3 const merged = [];
4 for (const interval of intervals) {
5 if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
6 merged.push(interval);
7 } else {
8 merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
9 }
10 }
11 return merged;
12};

Merge Intervals in Python, Java, C++, TypeScript and C

Merge Intervals in Python
def merge(intervals):
    intervals.sort(key=lambda x: x[0])
    merged = []
    for interval in intervals:
        if not merged or merged[-1][1] < interval[0]:
            merged.append(interval)
        else:
            merged[-1][1] = max(merged[-1][1], interval[1])
    return merged
Merge Intervals in Java
class Solution {
    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) return intervals;
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        LinkedList<int[]> merged = new LinkedList<>();
        for (int[] interval : intervals) {
            if (merged.isEmpty() || merged.getLast()[1] < interval[0]) {
                merged.add(interval);
            } else {
                merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}
Merge Intervals in C++
class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        sort(intervals.begin(), intervals.end());
        vector<vector<int>> merged;
        for (auto& interval : intervals) {
            if (merged.empty() || merged.back()[1] < interval[0]) {
                merged.push_back(interval);
            } else {
                merged.back()[1] = max(merged.back()[1], interval[1]);
            }
        }
        return merged;
    }
};
Merge Intervals in TypeScript
function merge(intervals: number[][]): number[][] {
    intervals.sort((a, b) => a[0] - b[0]);
    const merged: number[][] = [];
    for (const interval of intervals) {
        if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
            merged.push(interval);
        } else {
            merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
        }
    }
    return merged;
}
Merge Intervals in C
int cmp(const void* a, const void* b) {
    int* x = *(int**)a;
    int* y = *(int**)b;
    return (x[0] > y[0]) - (x[0] < y[0]);
}

int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) {
    qsort(intervals, intervalsSize, sizeof(int*), cmp);
    int** merged = malloc(intervalsSize * sizeof(int*));
    *returnColumnSizes = malloc(intervalsSize * sizeof(int));
    int count = 0;

    for (int i = 0; i < intervalsSize; i++) {
        if (count == 0 || merged[count - 1][1] < intervals[i][0]) {
            merged[count] = malloc(2 * sizeof(int));
            merged[count][0] = intervals[i][0];
            merged[count][1] = intervals[i][1];
            (*returnColumnSizes)[count++] = 2;
        } else if (intervals[i][1] > merged[count - 1][1]) {
            merged[count - 1][1] = intervals[i][1];
        }
    }
    *returnSize = count;
    return merged;
}