Imagine hosting a party where n friends (numbered 0 to n-1) arrive and leave at different times! The venue has an infinite number of chairs numbered from 0 to infinity, and there's one simple rule: when a friend arrives, they must sit in the lowest-numbered available chair.
Here's how it works:
- If chairs 0, 1, and 5 are occupied when someone arrives, they'll sit in chair
2 - When a friend leaves, their chair becomes available immediately
- If someone leaves and another person arrives at the exact same moment, the arriving person can take that chair
You're given a 2D array times where times[i] = [arrival_i, leaving_i] represents when friend i arrives and leaves. Your mission: find which chair number the targetFriend will sit on!
Note: All arrival times are distinct, so no two friends arrive simultaneously.
Input & Output
Visualization
Time & Space Complexity
O(n log n) for sorting + O(n log n) for heap operations (each friend does at most 2 heap operations)
O(n) space for heaps storing chairs and departure events
Constraints
- n == times.length
- 2 โค n โค 104
- times[i].length == 2
- 1 โค arrivali < leavingi โค 105
- 0 โค targetFriend โค n - 1
- All arrival times are distinct