Laundromat Machine Count

MediumintervalsAlso known as Meeting Rooms II

Your laundromat works by reservation. Customers book a washing machine for a window measured in minutes after opening. A booking of [10, 40] means the load starts at minute 10 and the machine is free again at minute 40, so it can take a load that starts at 40.

Machines are expensive, so given a busy Saturday's reservations, you want to know how few machines could have served everyone on time.

Your task

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

A load ending at time t and one starting at 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] and then [50, 95], and machine B runs [10, 40] and 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 runs all three back to back.

Constraints

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

For each load's start time t, scan the whole list to count loads running then (start ≤ t < end). The peak is the answer, because the busiest moment is always some load's start.

That is O(n²), which is about 100 million comparisons for 10,000 loads, and it 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