Merge Intervals

Merge all overlapping intervals.

Pattern

Sort + Merge

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.

Approach

How to Solve It

Sort by start. If current overlaps last merged, extend end. Otherwise, add new.

Key Insight

After sorting by start, overlapping intervals are adjacent — you only need to compare with the last merged interval, not scan backwards.

Step-by-step

  1. 1Sort intervals by start time
  2. 2Initialize result with the first interval
  3. 3For each subsequent interval:
  4. 4If it overlaps with the last interval in result, extend the end
  5. 5Otherwise, add it as a new interval

Pseudocode

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 result
Complexity Analysis

Time Complexity

O(n log n)

Space Complexity

O(n)
More Intervals Problems

Master this pattern with YeetCode

Practice Merge Intervals and similar Intervals problems with flashcards. Build pattern recognition through active recall.

Practice this problem