How many rooms?
Find the fewest rooms that hold all meetings at once by sorting starts and ends separately and sweeping through time. About 18 minutes.
Starts and ends, apart
A meeting is [start, end), so one ending at 10 and another starting at 10 can share a room. You need the fewest rooms for all meetings.
Which meeting is in which room does not matter. All that matters is how many are running at one time. So pull the starts and the ends apart into two sorted lists. Time moves forward: a start takes a room, an end gives one back.
Reuse or open
Go through the starts in order, with a pointer j at the earliest end not yet used. If the next start is at or after that end, some meeting has finished, so its room is free: reuse it and move j along.
Otherwise every meeting so far is still running, so open a new room. The number of rooms opened is the answer, and each list is walked once after sorting.
starts.sort() ends.sort()
Start 1: no meeting has ended yet. Open room 1.
Meetings [1, 3] and [3, 5]. How many rooms?
- A1
- B2
- C3
Show the answer
1. The first ends at 3 as the second starts at 3, so the room is free.
Meeting rooms needed
You are given meetings, each as [start, end), meaning it occupies the room from start up to but not including end. Return the fewest rooms needed to hold all the meetings.
meetings = [[0, 30], [5, 10], [15, 20]] → 2
0 ≤ meetings.length ≤ 100,000 · 0 ≤ start < end ≤ 1,000,000,000