MediumNo. 0056
Merge Intervals — LeetCode 56 Python Solution
- Pattern
- Sorting
- Topics
- Array, Sorting
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0164 | Maximum Gap | Medium |
| 0274 | H-Index | Medium |
| 0406 | Queue Reconstruction by Height | Medium |
| 0414 | Third Maximum Number | Easy |
| 0462 | Minimum Moves to Equal Array Elements II | Medium |
| 0539 | Minimum Time Difference | Medium |
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.