Difficulty: Medium | Asked at: Meta, Google, LinkedIn
Given a list of intervals, merge all overlapping ones.
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
💡 Hint: Overlaps are much easier to spot once the intervals are sorted by start time.
Solution:
python
def merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
last_end = merged[-1][1]
if start <= last_end:
merged[-1][1] = max(last_end, end)
else:
merged.append([start, end])
return merged
Complexity: O(n log n) - dominated by the sort. The merge pass itself is O(n).
Common mistake: Forgetting
max(last_end, end) and just assuming end is always bigger. Consider [[1,10],[2,3]] - the second interval is fully contained in the first, so if you don't take the max, you'd shrink your merged interval incorrectly.This pattern (sort, then single pass comparing to the last processed item) shows up in a TON of interval problems. Recognize it and you'll fly through similar questions.
What's your go-to strategy when you see "intervals" in a problem? 👇