โ† Back to Heap Pattern

๐Ÿ“š The Number of the Smallest Unoccupied Chair โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The problem involves finding the smallest unoccupied chair for a specific friend arriving at a party. Each friend has an arrival and departure time, and chairs are assigned in increasing order starting from 0. When a chair becomes unoccupied, it can be reassigned to another friend.

To solve this efficiently, we use two heaps:

๐Ÿงฑ Pattern Template

class Solution {
    public int smallestChair(int[][] times, int targetFriend) {
        int n = times.length;
        int targetArrival = times[targetFriend][0];

        // Step 1: Sort times by arrival time
        int[][] indexedTimes = new int[n][3];
        for (int i = 0; i < n; i++) {
            indexedTimes[i][0] = times[i][0]; // Arrival time
            indexedTimes[i][1] = times[i][1]; // Departure time
            indexedTimes[i][2] = i; // Friend index
        }
        Arrays.sort(indexedTimes, (a, b) -> a[0] - b[0]);

        // Step 2: Initialize heaps
        PriorityQueue availableChairs = new PriorityQueue<>();
        PriorityQueue occupiedChairs = new PriorityQueue<>((a, b) -> a[0] - b[0]); // [departureTime, chair]

        // Add all chairs to the availableChairs heap
        for (int i = 0; i < n; i++) {
            availableChairs.offer(i);
        }

        // Step 3: Process each friend
        for (int[] time : indexedTimes) {
            int arrival = time[0];
            int departure = time[1];
            int friendIndex = time[2];

            // Free up chairs that have been vacated
            while (!occupiedChairs.isEmpty() && occupiedChairs.peek()[0] <= arrival) {
                availableChairs.offer(occupiedChairs.poll()[1]);
            }

            // Assign the smallest available chair
            int chair = availableChairs.poll();
            if (friendIndex == targetFriend) {
                return chair;
            }

            // Mark the chair as occupied
            occupiedChairs.offer(new int[]{departure, chair});
        }

        return -1; // Should never reach here
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: The Number of the Smallest Unoccupied Chair

Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1

Explanation:
- Friend 0 arrives at 1 and takes chair 0.
- Friend 1 arrives at 2 and takes chair 1.
- Friend 0 leaves at 4, freeing chair 0.
- Friend 2 arrives at 4 and takes chair 0.
- Target friend (1) is assigned chair 1.

๐Ÿ’ก Pro Tips