This problem follows the Sort + Merge pattern, commonly found in the Intervals category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Sort by start. If current overlaps last merged, extend end. Otherwise, add new.
After sorting by start, overlapping intervals are adjacent — you only need to compare with the last merged interval, not scan backwards.
intervals.sort(key=lambda x: x[0])
result = [intervals[0]]
for start, end in intervals[1:]:
if start <= result[-1][1]:
result[-1][1] = max(result[-1][1], end)
else:
result.append([start, end])
return resultPractice Merge Intervals and similar Intervals problems with flashcards. Build pattern recognition through active recall.
Practice this problem