Skip to content

Meeting Rooms II

MediumLeetCode #253PremiumTime O(n log n)Space O(n)

You get a list of meetings as [start, end]. Return the smallest number of rooms that lets every meeting happen. A meeting that ends at time t and another that starts at t can use the same room.

[[0,30],[5,10],[15,20]] -> 2
[[1,5],[5,10]] -> 1

In the first example, [0,30] runs all day, and the other two never overlap each other, so they share the second room.

The answer is the largest number of meetings running at the same moment. Checking every meeting against every room is O(n²).

Notice you don’t need to know which meeting ends, only when the earliest one does. So separate the times: sort all starts, and sort all ends independently. Walk through the starts in order. If the next start is before the earliest unused end, every room is still busy, so add a room. Otherwise some meeting has finished: reuse its room by moving to the next end. The ends pointer only moves when a room is reused.

The common alternative is a min-heap of end times. Sort by start, and for each meeting pop the heap if its smallest end is <= start, then push the new end. The heap size at the end is the answer. Same O(n log n), but you must have a heap (TypeScript has none).

Show solutionHide solution
def min_meeting_rooms(intervals: list[list[int]]) -> int:
starts = sorted(s for s, _ in intervals)
ends = sorted(e for _, e in intervals)
rooms = 0
e = 0 # earliest end time not yet "freed"
for start in starts:
if start < ends[e]:
rooms += 1 # nobody has finished yet: need a new room
else:
e += 1 # someone finished by now: reuse their room
return rooms
  • Time: O(n log n) — two sorts; the sweep itself is O(n).
  • Space: O(n) — the two arrays of starts and ends.
  • Use < for the busy check. start < ends[e] means the earlier meeting is still running. When start == ends[e] the room is free, so that branch reuses it.
  • Sort starts and ends separately. This is fine here because only the counts matter, not which start pairs with which end. It would be wrong if you needed assignments.
  • Empty input. Return 0. The loop never runs, so ends[0] is never read.

Can one person attend all meetings? The trick: sort by start and check that each meeting begins at or after the previous one ends. Any overlap means no.

Minimum Number of Arrows to Burst Balloons (LeetCode 452)

Section titled “Minimum Number of Arrows to Burst Balloons (LeetCode 452)”

Balloons are horizontal ranges; one arrow pops every balloon it crosses. The trick: sort by end and shoot at the end of the first balloon. Skip every balloon that starts at or before that point, then shoot again at the next uncovered one.

Trips pick up and drop off passengers; is the capacity ever exceeded? The trick: the sweep line. Add +passengers at each pickup and -passengers at each drop-off, process in time order, and check the running total never goes above capacity.