Merge Intervals
LeetCode 56 · Medium · solution, intuition & step-by-step walkthrough
Sort by start; extend or append.
This is how I solved Merge Intervals (LeetCode 56), a medium problem from the Sorting pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Sort by start time. Then each interval either starts after the last merged one ends (start a new block) or overlaps it (extend the end). One pass does the job.
Approach
- 1
Sort intervals by start.
- 2
If merged is empty or the start is beyond the last end, append.
- 3
Otherwise extend the last end to max(end, last end).
How I solved it
Sort + sweepPythonO(n log n) time
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
merged=[]
intervals.sort(key=lambda x:x[0])
for start,end in intervals:
if len(merged)==0 or start>merged[-1][1]:
merged.append([start,end])
else:
merged[-1][1]=max(merged[-1][1],end)
return merged
Merge Intervals — FAQ
What is the intuition behind Merge Intervals?
Sort by start time. Then each interval either starts after the last merged one ends (start a new block) or overlaps it (extend the end). One pass does the job.
How do you solve Merge Intervals (LeetCode 56)?
1. Sort intervals by start. 2. If merged is empty or the start is beyond the last end, append. 3. Otherwise extend the last end to max(end, last end).
What is the time and space complexity of Merge Intervals?
Time: O(n log n). Space: O(n). (Accepted approach: Sort + sweep.)
What are common mistakes in Merge Intervals?
Touching intervals like [1,4] and [4,5] count as overlapping.