Skip to content
DSA in JavaScript
← All patterns

Overlapping Intervals

0/15 solved

What it is

Sort ranges by their start, then walk through them once, comparing each with the previous one to see if they overlap.

Used for

Merge ranges, insert a range, meeting rooms, finding free time.
[1,3]
[2,6]
[8,10]
[9,12]
0123456789101112

Step 1 of 6

Goal: merge overlapping time ranges, like meetings. Sort them by start time first, so an overlap can only be with the range just before.

You see

  • Ranges with a start and end
  • Merge, insert or schedule
  • Minimum rooms or removals

Learn it in

Jump Game

Template

function mergeIntervals(iv) {  iv.sort((a, b) => a[0] - b[0]);  const out = [iv[0]];  for (const [s, e] of iv.slice(1)) {    const last = out.at(-1);    s <= last[1] ? (last[1] = Math.max(last[1], e)) : out.push([s, e]);  }  return out;}

Practice problems