Bank app~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
You work on the booking system of a bank branch. Customers book appointments with advisors, and each appointment needs a room for a time span. After an appointment, staff clean and reset the room, which takes a fixed number of minutes.
The branch numbers its rooms 1, 2, 3 and so on. A new appointment takes the lowest-numbered room that is free. Your team lead asks: "Which room does each appointment get, and how many rooms does the branch need?" The log holds up to 200,000 appointments.
Write assign_rooms(meetings, gap).
meetings[i] = [start, end] is appointment i, with start < end. The list is not sorted.start. When two start at the same minute, handle the one that comes first in the list first.end can host another appointment from the minute end + gap.Input: meetings = [[9, 12], [0, 5], [4, 8], [5, 9], [8, 11], [12, 14]], gap = 1
Output: [2, 1, 2, 3, 1, 1]| Appointment (index) | Span | Rooms free at its start | Room used | Busy until |
|---|---|---|---|---|
| 1 | 0 to 5 | none | 1, new | 6 |
| 2 | 4 to 8 | none | 2, new | 9 |
| 3 | 5 to 9 | none | 3, new | 10 |
| 4 | 8 to 11 | 1 | 1 | 12 |
| 0 | 9 to 12 | 2 | 2 | 13 |
| 5 | 12 to 14 | 1 and 3 | 1, the lowest | 15 |
The branch needs 3 rooms.
Input: meetings = [[1, 4]], gap = 5
Output: [1]Input: meetings = [[0, 10], [3, 6], [7, 9]], gap = 0
Output: [1, 2, 2]With no gap, room 2 is free again at minute 6, and the third appointment starts at minute 7.
1 ≤ meetings.length ≤ 200,000 (appointments)0 ≤ start < end ≤ 1,000,000,0000 ≤ gap ≤ 1,000,000,000end + gap can reach 2,000,000,000, which is close to the limit of a 32-bit integer.If all appointments overlap, the branch needs 200,000 rooms. Looking through the rooms for a free one costs up to 200,000 steps for each appointment, about 20,000,000,000 steps in all.
A heap of busy rooms, ordered by the time they become free, shows which rooms are free in a few steps. A second heap of free rooms, ordered by number, gives the lowest one in a few steps. That is about 200,000 × 3 × 18 = 10,800,000 steps.