Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Module 08 · DSA · Worked problems, in English · about 16 min to read

Play it as a journeyTutor comes with a plan

Clinic #28: Merge Intervals

Meeting Rooms II
Meeting Rooms II · Open board

A board drawn in Hinglish for a problem about booking meeting rooms: bars laid along a timeline, each one a stretch from a start to an end. This lesson asks those same bars a different question, and the board’s panel on spotting the pattern already files it under “sort by start”.

Checking every pair among ten thousand items is about how many pairs?

50,10,00,000 pairs

Before you start. Sorting a list takes a little more than one pass over it: ten times the items costs about thirteen times the work, which engineers write as O(n log n), and Sorting & Searching shows where that comes from. Reading every item once is O(n), and reading every pair of items is O(n²), which at ten thousand items is fifty million pairs.

Lesson 67 of 96 in DSA

The rest of this lesson is part of a plan.

A plan opens every lesson, board, video, lab and paper on chalk. Yearly is $39/year.

See plansAlready a member? Sign in

Or start free: a free account opens lessons 2 and 3 of every track.

In this lesson

  • The traffic desk: one sign per closed stretch of road
  • By hand: four crews, three signs, and the word interval
  • The wrong first idea: read the notices in the order they arrived
  • Sort by start: walk the road in order
  • Overlap: one comparison against the sign in your hand
  • Merge: stretch the end, never shrink it
  • The invariant: everything behind you is final
  • Not the same question as Meeting Rooms II
  • Brute force: merge any pair until nothing changes · O(n³) worst case
  • Better: an overlap graph · O(n²)
  • Best: sort by start, one pass · O(n log n) time, O(n) space
  • The three wrong versions, side by side
  • The bug that passes every row above: appending the caller’s list
  • The Meeting Rooms counter, asked the merge question
  • Timings
  • In an interview
  • The interval ladder: easy, medium, hard

Terms it explains: O(n log n), O(n), O(n²), interval, overlap, merge, invariant, Write the pass,, Insert Interval, end.

Review DSA