KatInterview

56. Merge Intervals

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to merge a collection of intervals that overlap. Given a list of intervals, where each interval is defined by a start and an end point, we need to produce a new list of intervals where any overlapping intervals are combined into a single, larger interval. For example, [1,3] and [2,6] overlap and should be merged into [1,6]. Intervals like [1,4] and [4,5] are also considered overlapping.

Solution

Merge Intervals in Python

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        # Sort the intervals based on their start time.
        # The `key=lambda x: x[0]` argument tells sort to use the first element
        # of each sublist as the sorting key.
        intervals.sort(key=lambda x: x[0])
        
        merged = []
        for interval in intervals:
            # If the `merged` list is empty, or if the current interval
            # does not overlap with the last interval in `merged`, append it.
            # An overlap does not occur if the current interval's start is greater than
            # the previous interval's end.
            if not merged or interval[0] > merged[-1][1]:
                merged.append(interval)
            else:
                # There is an overlap, so we merge the current interval with the last one.
                # We update the end of the last interval in `merged` to be the maximum of
                # its current end and the current interval's end.
                merged[-1][1] = max(merged[-1][1], interval[1])
                
        return merged

Merge Intervals in Java

class Solution {
    public int[][] merge(int[][] intervals) {
        // If there are 0 or 1 intervals, no merging is needed.
        if (intervals.length <= 1) {
            return intervals;
        }

        // Sort intervals based on their start time.
        // We use a lambda expression `(a, b) -> Integer.compare(a[0], b[0])`
        // as a comparator, which sorts based on the first element of each sub-array.
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

        // Use a list to store the merged intervals as its size is dynamic.
        List<int[]> merged = new ArrayList<>();
        for (int[] interval : intervals) {
            // If the `merged` list is empty, or if the current interval
            // does not overlap with the last interval in `merged`, simply add it.
            // An overlap does not occur if the current interval's start is greater than
            // the previous interval's end.
            if (merged.isEmpty() || interval[0] > merged.get(merged.size() - 1)[1]) {
                merged.add(interval);
            } else {
                // There is an overlap, so we merge the current interval with the last one.
                // We update the end of the last interval in `merged` to be the maximum of
                // its current end and the current interval's end.
                merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
            }
        }

        // Convert the list back to a 2D array to match the required return type.
        return merged.toArray(new int[merged.size()][]);
    }
}

Merge Intervals in C++

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        // If there are 0 or 1 intervals, no merging is needed.
        if (intervals.size() <= 1) {
            return intervals;
        }

        // Sort intervals based on their start time.
        // The lambda function `[](const auto& a, const auto& b) { return a[0] < b[0]; }`
        // compares two intervals `a` and `b` based on their first element (start time).
        sort(intervals.begin(), intervals.end());

        vector<vector<int>> merged;
        for (const auto& interval : intervals) {
            // If the `merged` list is empty, or if the current interval
            // does not overlap with the last interval in `merged`, simply add it.
            // An overlap does not occur if the current interval's start is greater than
            // the previous interval's end.
            if (merged.empty() || interval[0] > merged.back()[1]) {
                merged.push_back(interval);
            } else {
                // There is an overlap, so we merge the current interval with the last one.
                // We update the end of the last interval in `merged` to be the maximum of
                // its current end and the current interval's end.
                merged.back()[1] = max(merged.back()[1], interval[1]);
            }
        }

        return merged;
    }
};

Merge Intervals in TypeScript

function merge(intervals: number[][]): number[][] {
    // If there are 0 or 1 intervals, no merging is needed.
    if (intervals.length <= 1) {
        return intervals;
    }

    // Sort intervals based on their start time.
    // The comparison function `(a, b) => a[0] - b[0]` sorts the array
    // of arrays based on the first element of each inner array.
    intervals.sort((a, b) => a[0] - b[0]);

    const merged: number[][] = [];
    for (const interval of intervals) {
        // If the `merged` list is empty, or if the current interval
        // does not overlap with the last interval in `merged`, simply add it.
        // An overlap does not occur if the current interval's start is greater than
        // the previous interval's end.
        if (merged.length === 0 || interval[0] > merged[merged.length - 1][1]) {
            merged.push(interval);
        } else {
            // There is an overlap, so we merge the current interval with the last one.
            // We update the end of the last interval in `merged` to be the maximum of
            // its current end and the current interval's end.
            merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
        }
    }

    return merged;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.