Leetcode 1942: The Number of the Smallest Unoccupied Chair

grid47
grid47
Exploring patterns and algorithms
Apr 26, 2024 7 min read

In a party, there are n friends with distinct arrival and departure times. Each friend chooses the smallest available chair. The task is to determine the chair number where the friend numbered targetFriend will sit.
Problem
Approach
Steps
Complexity
Input: A 2D array times where times[i] = [arrivali, leavingi] indicates the arrival and leaving times of the ith friend, and an integer targetFriend representing the index of the target friend.
Example: times = [[1,5],[2,6],[3,8]], targetFriend = 1
Constraints:
• 2 <= n <= 10^4
• 1 <= arrivali < leavingi <= 10^5
• Each arrival time is distinct
• 0 <= targetFriend < n
Output: Return the chair number that the target friend will sit on.
Example: Output: 1
Constraints:
• The output is an integer representing the chair number.
Goal: The goal is to determine the chair number occupied by the target friend.
Steps:
• Sort the friends based on their arrival times.
• Use two priority queues: one for keeping track of the available chairs and another for tracking the chairs occupied by friends based on their leaving times.
• Assign the smallest available chair to each arriving friend and release the chair when a friend leaves.
• Check when the target friend arrives and assign their chair number.
Goal: The array contains the arrival and departure times for each friend. The times are within the given range, and the number of friends is manageable within the problem's constraints.
Steps:
• 2 <= n <= 10^4
• 1 <= arrivali < leavingi <= 10^5
• Each arrival time is distinct
• 0 <= targetFriend < n
Assumptions:
• The arrival and departure times for each friend are unique and provided in a correct format.
Input: Example 1: times = [[1, 5], [2, 6], [3, 8]], targetFriend = 1
Explanation: Friend 0 arrives at time 1 and sits on chair 0. Friend 1 arrives at time 2 and sits on chair 1. Friend 2 arrives at time 3 and sits on chair 2. At time 5, Friend 0 leaves and Friend 1 sits back in chair 0. Friend 2 stays until time 8. Since Friend 1 sits on chair 1, the answer is 1.

Input: Example 2: times = [[1, 3], [2, 5], [3, 7], [4, 6]], targetFriend = 2
Explanation: Friend 0 arrives at time 1 and sits on chair 0. Friend 1 arrives at time 2 and sits on chair 1. Friend 2 arrives at time 3 and sits on chair 2. Friend 1 leaves at time 5, Friend 2 leaves at time 7, and Friend 3 arrives at time 4. The target friend 2 sits on chair 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus