MediumNo. 0056

Merge Intervals — LeetCode 56 Python Solution

Pattern
Sorting
Topics
Array, 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

PythonSolution
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

Time
O(n × log n)
Space · auxiliary
O(log n)

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

Related problems
No.ProblemDifficulty
0164Maximum GapMedium
0274H-IndexMedium
0406Queue Reconstruction by HeightMedium
0414Third Maximum NumberEasy
0462Minimum Moves to Equal Array Elements IIMedium
0539Minimum Time DifferenceMedium

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.