High interview relevanceRoadmap: Intermediate
TimeO(n log n)
SpaceO(n)

Why it costs this much

Sorting by start time costs O(n log n), and one pass then merges neighbors in O(n).

Code

def merge(intervals):
    out = []
    for s, e in sorted(intervals):             # O(n log n)
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)    # extend the previous interval
        else:
            out.append([s, e])                 # one O(n) pass
    return out

Common pitfalls

Forgetting to sort is the usual bug. Decide up front whether intervals that only touch (end equals next start) should merge.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list