Meeting Rooms III — LeetCode 2402 Python Solution

HardArrayHash TableSortingSimulationHeap (Priority Queue)
Problem
#2402
Reading time
4 min

The problem

You are given an integer n. There are n rooms numbered from 0 to n - 1.

Example

Input
n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
Output
0
Explanation
- At time 0, both rooms are not being used. The first meeting starts in room 0.

Python solution

Python
class Solution:
    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
        meetings.sort(key=lambda x: x[0])
        busy = []
        idle = list(range(n))
        heapify(idle)
        cnt = [0] * n
        for s, e in meetings:
            while busy and busy[0][0] <= s:
                heappush(idle, heappop(busy)[1])
            i = 0
            if idle:
                i = heappop(idle)
                heappush(busy, (e, i))
            else:
                time_end, i = heappop(busy)
                heappush(busy, (time_end + e - s, i))
            cnt[i] += 1
        ans = 0
        for i in range(n):
            if cnt[ans] < cnt[i]:
                ans = i
        return ans

Complexity

MeasureComplexity
TimeO(m (\log m + \log n))
SpaceO(n + m), where n and m are the number of meeting rooms and meetings respectively auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2402. Meeting Rooms III is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2402. Meeting Rooms III?
LeetCode 2402. Meeting Rooms III is rated Hard on LeetCode.
What is the time complexity of LeetCode 2402. Meeting Rooms III?
The Python solution on this page runs in O(m (\log m + \log n)).
What is the space complexity of LeetCode 2402. Meeting Rooms III?
The Python solution on this page uses O(n + m), where n and m are the number of meeting rooms and meetings respectively auxiliary space.
What topics does LeetCode 2402. Meeting Rooms III cover?
LeetCode 2402. Meeting Rooms III is tagged Array, Hash Table, Sorting, Simulation and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview