Leetcode 2054 Solution

This article provides solution to leetcode question 2054 (the-number-of-the-smallest-unoccupied-chair)

https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair

Solution

class Solution:
    def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
        events = []
        for i, (start, end) in enumerate(times):
            events.append((start, 1, i))
            events.append((end, -1, i))

        events.sort()

        available = list(range(len(times)))
        heapq.heapify(available)

        taken = {}

        for t, op, friend_id in events:
            if op == 1:
                seat = heapq.heappop(available)
                taken[friend_id] = seat

                if friend_id == targetFriend:
                    return seat
            elif op == -1:
                seat = taken[friend_id]
                del taken[friend_id]
                heapq.heappush(available, seat)