Laundromat Machine Count

MediumintervalsAlso known as Meeting Rooms II

You are opening a laundromat that works by reservation. Customers book a washing machine for a time window, in minutes after opening: [10, 40] means they load at minute 10 and the machine is free again at minute 40. A machine that frees up at minute 40 can take a new load that starts at minute 40.

Machines are expensive. Looking at a busy Saturday's reservations, how few machines could have served every customer on time?

Your task

Write machinesNeeded(loads). Each load is [start, end] with start < end. Return the minimum number of machines so that every load can run on some machine, and no machine runs two loads at once.

A load ending at time t and another starting at time t can share a machine. An empty list needs 0 machines.

machinesNeeded(loads: int[][]) → int

Examples

Example 1
Input
loads = [[0, 45], [10, 40], [40, 70], [50, 95]]
Output
2
Why

From minute 10 to 40 two loads run at once, so you need at least 2 machines. And 2 is enough: machine A runs [0, 45] then [50, 95]; machine B runs [10, 40] then [40, 70].

Example 2
Input
loads = [[30, 60], [60, 90], [90, 120]]
Output
1
Why

Each load starts exactly when the previous one ends, so one machine handles all three back to back.

Constraints

  • 0 ≤ loads.length ≤ 10,000
  • 0 ≤ start < end ≤ 1,000,000,000
Start with brute force

For every load's start time, count how many loads are running at that moment (start ≤ t < end) by scanning the whole list. The peak count is the answer, because the busiest moment is always some load's start.

That is n checks of n loads each: O(n²), about 100 million comparisons for 10,000 loads. The scan recounts the same loads again and again; sorting lets you keep a running count instead.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code