Loading...
Loading...
You are building a room reservation system for a co-working space. Given a list of bookings where each booking has a start and end timestamp (in minutes), determine the peak concurrent occupancy — the maximum number of bookings that overlap at any single point in time.
A booking
[s, e]occupies the room during the interval[s, e)(inclusive start, exclusive end). Two bookings overlap if one starts before the other ends.
bookings where bookings[i] = [start_i, end_i][start_i, end_i)Input: bookings = [[1, 4], [2, 6], [5, 8]]
Output: 2
Explanation:
Input: bookings = [[1, 10], [2, 8], [3, 7], [4, 6]]
Output: 4
Explanation: All four bookings overlap at time 4. Peak is 4.
Input: bookings = [[1, 3], [4, 6], [7, 9]]
Output: 1
Explanation: No two bookings overlap (they are back-to-back with exclusive ends). Peak is 1.
Brute Force (O(n²)): For every booking, count how many other bookings overlap with it. Return the maximum count. This will be too slow for large inputs.
Efficient Approach — Event Sweep (O(n log n)):
[s, e] into two events: a +1 at time s (arrival) and a -1 at time e (departure).This approach runs in O(n log n) time due to sorting, and O(n) space for the events array.
0 <= bookings.length <= 10^5 0 <= start_i < end_i <= 10^9