Back to Practice
#0034

Merge Overlapping Intervals

MediumDSA20 min15 XP

Problem

Given intervals [start, end], merge all overlapping intervals and return the merged list sorted by start.

Why This Matters

Intervals show up in calendars, booking systems, logs, timelines, and scheduling interviews.

Function Signature

def merge_intervals(intervals):

Examples

Example 1
Inputintervals = [[1,3], [2,6], [8,10], [15,18]]
Output[[1,6], [8,10], [15,18]]

[1,3] and [2,6] overlap, so they become [1,6].

Constraints

  • Each interval has start <= end.
  • Input may be unsorted.
  • Touching intervals, like [1,3] and [3,5], should merge.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Classic overlap
Input[[1,3], [2,6], [8,10], [15,18]]
Expected[[1,6], [8,10], [15,18]]

Only the first two intervals overlap.

Touching intervals
Input[[1,3], [3,5]]
Expected[[1,5]]

start <= previous end means the intervals connect.

Hidden Test Categories
Empty listAlready merged intervalsUnsorted intervalsOne interval contained inside another