Merge Intervals — LeetCode 56 Python Solution

MediumArraySorting
Problem
#56
Pattern
Sorting
Reading time
2 min

The problem

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example

Input
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output
[[1,6],[8,10],[15,18]]
Explanation
Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Python solution

Python
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort()
        ans = []
        st, ed = intervals[0]
        for s, e in intervals[1:]:
            if ed < s:
                ans.append([st, ed])
                st, ed = s, e
            else:
                ed = max(ed, e)
        ans.append([st, ed])
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 56. Merge Intervals is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 56. Merge Intervals?
LeetCode 56. Merge Intervals is rated Medium on LeetCode.
What is the time complexity of LeetCode 56. Merge Intervals?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 56. Merge Intervals?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 56. Merge Intervals cover?
LeetCode 56. Merge Intervals is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview