Skip to Content

Sort intervals by start, then sweep and merge any that overlap.

Data Flow

input:  (1,4) (3,6) (8,10) (9,12) (15,18)

sort by start: (1,4) (3,6) (8,10) (9,12) (15,18)

scan:
   (1,4) ----> merge with (3,6) -> (1,6)
   (8,10) ---> merge with (9,12) -> (8,12)
   (15,18) emitted as-is

result: (1,6) (8,12) (15,18)

When to use

Code

def merge(intervals):
    intervals.sort(key=lambda x: x[0])
    out = []
    for s, e in intervals:
        if out and s <= out[-1][1]:                 # overlaps
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out

Pitfalls

Analogy

Compressing your calendar: overlapping meetings collapse into a single block whose end is the latest of all overlapping events.

Interview tip: After merging, re-check the original question — it is often “how many rooms are needed?” rather than “give me back the merged list”. The pattern still applies.

Advertisement