LeetCode 1942: The Number of the Smallest Unoccupied Chair Solution
Master LeetCode problem 1942 (The Number of the Smallest Unoccupied Chair), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1942. The Number of the Smallest Unoccupied Chair
Problem Explanation
Explanation:
- We can simulate the process of friends arriving and leaving the party.
- We can maintain two priority queues, one for available chairs and one for occupied chairs.
- We iterate through the times array in chronological order.
- For each friend's arrival, we assign them the smallest available chair.
- When a friend leaves, we mark their chair as available again.
- We keep track of the chair assigned to the targetFriend and return it at the end.
Time Complexity: O(n log n), where n is the number of friends arriving and leaving. Space Complexity: O(n), where n is the number of friends arriving and leaving.
Solution Code
import java.util.*;
class Solution {
public int smallestChair(int[][] times, int targetFriend) {
PriorityQueue<Integer> availableChairs = new PriorityQueue<>();
PriorityQueue<int[]> occupiedChairs = new PriorityQueue<>((a, b) -> a[1] - b[1]);
int[] targetFriendTimes = null;
for (int i = 0; i < times.length; i++) {
availableChairs.offer(i);
}
for (int[] time : times) {
while (!occupiedChairs.isEmpty() && occupiedChairs.peek()[1] <= time[0]) {
int chair = occupiedChairs.poll()[0];
availableChairs.offer(chair);
}
int friend = time[0];
int chair = availableChairs.poll();
if (friend == times[targetFriend][0]) {
targetFriendTimes = new int[]{chair, time[1]};
}
occupiedChairs.offer(new int[]{chair, time[1]});
}
return targetFriendTimes[0];
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1942 (The Number of the Smallest Unoccupied Chair)?
This page provides optimized solutions for LeetCode problem 1942 (The Number of the Smallest Unoccupied Chair) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1942 (The Number of the Smallest Unoccupied Chair)?
The time complexity for LeetCode 1942 (The Number of the Smallest Unoccupied Chair) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1942 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1942 in Java, C++, or Python.