Skip to content
Optimal Lab

DSA · interactive

Merge overlapping intervals

Meetings, bookings, time ranges: combine the ones that overlap. Comparing every pair is slow. Sort by start time first, and then each interval only needs to be compared with the last merged one.

Input, sorted by start

  • 8–10
  • 1–3
  • 15–18
  • 2–6
  • 9–12
  • 17–19
  • 4–5

Merged

01020

Sort by start time. Now any overlap is with the interval just before.

step 1 of 9
  1. 1

    After sorting, an interval can only overlap the one directly before it (or the merged block it joined).

    intervals.sort((a, b) => a[0] - b[0])

  2. 2

  3. 3

  4. 4

In production

Tools and technologies

Interval merging runs in calendars and genome tools.

Not tied to one language — use these names when you search docs or design a system.