Greedy

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Sort intervals by start and combine overlapping neighbors.

Step 1 / 5
Problem shape
Current lesson

Merge Intervals Lab

Greedy Beginner

Merge Intervals

Welcome to the Merge Intervals algorithm lab. Sort intervals by start and combine overlapping neighbors. Use it when: Use for calendars, ranges, timelines, and overlap normalization. The time complexity is O(n log n), and the space complexity is O(n). The pseudocode is: sort intervals by start for interval in intervals if output empty or interval.start > last.end append interval else last.end = max(last.end, interval.end) As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n log n)

Space

O(n)

Pseudocode

sort intervals by start
for interval in intervals
  if output empty or interval.start > last.end
    append interval
  else
    last.end = max(last.end, interval.end)
Open deeper structure lesson
1.0x