Workspace / Learning hub
Heap / Top KDSA ROADMAP · 12 / 30
LESSON 12 · PATTERN GUIDE

Intervals

Sort and reason about ranges to merge overlaps, find conflicts, or select non-overlapping intervals.

FIRST, LEARN THE PATTERNSorting by start or end makes local comparisons sufficient for many interval tasks.

Inputs contain start/end pairs, meetings, bookings, or ranges that can overlap or touch.

How to approach it

For merging, sort by start and extend the current interval while the next start overlaps; otherwise emit and begin another.

Watch out for

Clarify whether touching endpoints count as overlapping and whether intervals are open, closed, or half-open.

A CLOSER EXPLANATION

Sorting gives intervals a predictable order, so each new interval only needs comparison with the current merged range. For scheduling non-overlaps, sorting by finish time is often the useful order. Always decide whether equal endpoints touch or overlap before writing comparisons.

NOW YOU TRY

Practice question

Merge overlapping intervals in [[1, 3], [2, 5], [7, 8]].

EXAMPLEintervals = [[1, 3], [2, 5], [7, 8]]Give your answer before revealing the explanation.
Show a hint

Sort by start and compare each interval with the end of the merged range.

Show an answer

[[1, 5], [7, 8]]

CONNECT IT TO REAL LIFE

Intervals at work

A clinic has appointment blocks [9:00, 10:00], [9:30, 10:30], and [11:00, 11:30]. What busy ranges should appear on the staff calendar?

Show one possible approach

[9:00, 10:30] and [11:00, 11:30]. Sort by start and merge the first two because they overlap.

Practice next

Use these problem IDs to find additional practice for this pattern:

5657252253435452