Booked Time and Peak Room Demand for a Schedule
Greedy & IntervalsAuto-graded · 21 test casesLast updated
Compute the total time covered by a set of half-open intervals and the maximum number of simultaneously active intervals, ignoring empty or reversed ones.
Booked Time and Peak Room Demand
A calendar holds a list of bookings. Each booking is a pair (start, end) of integers describing the half-open time range [start, end): the booking occupies start but not end.
Write a function that returns two numbers as a pair (covered, rooms):
covered: the total length of time during which at least one booking is active. Time where several bookings overlap is counted only once.rooms: the smallest number of rooms that lets every booking take place as scheduled, which equals the largest number of bookings active at the same moment.
Rules
- A booking with
start >= endhas no duration. It must be ignored completely and affects neither value. - Because ranges are half-open, two bookings that merely touch do not overlap. For example,
(1, 3)and(3, 5)can share one room. - The input may be in any order and may contain duplicates.
- If no valid booking remains (including an empty list), return
(0, 0).
Input
intervals: a list of(start, end)pairs of integers.
Output
- A pair
(covered, rooms)of integers.
Constraints
- The number of bookings
nmay be zero or larger; anO(n log n)solution is expected. - Start and end values are integers and may be negative or zero.
- Bookings with
start >= endare possible and must be ignored. - The list is not guaranteed to be sorted.
Examples
Example 1
Input: booked_time_and_rooms([[1, 4], [2, 5], [7, 9]])
Output: [6, 2]
Example 2
Input: booked_time_and_rooms([[1, 3], [3, 5]])
Output: [4, 1]
Example 3
Input: booked_time_and_rooms([[2, 2], [4, 4], [-1, -1]])
Output: [0, 0]
Hints
Hint 1
The two answers need different ideas: one is about the union of the ranges, the other about the deepest overlap at any single moment.
Hint 2
For the covered time, sort by start and merge ranges, extending the current block's end with a max whenever the next range begins no later than that end.
Hint 3
For the rooms, create +1 events at starts and -1 events at ends, and sort so that at equal times the -1 comes first. The peak running total is the answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two values answer different questions, so compute them separately.
Filtering. Drop every booking with start >= end. If nothing remains, return (0, 0).
Covered time (merge). Sort the valid bookings by start. Keep a current block [block_start, block_end). For each next booking:
- If its start is greater than
block_end, there is a real gap: add the block's length to the total and begin a new block. - Otherwise it overlaps or touches the block, so set
block_end = max(block_end, end).
After the loop, add the last block's length.
Rooms (sweep line). Make a +1 event at each start and a -1 event at each end. Sort by (time, delta), so at equal times the -1 is handled before the +1. Walk through the events, maintain the running count of active bookings, and record its maximum.
Why it is correct
- After sorting by start, once a booking begins strictly after
block_end, no later booking can reach back into the block, so closing it is safe. The closed blocks are disjoint and together form the union, so summing their lengths counts each moment once. Merging touching ranges does not change the sum, since there is no gap between them. - At any time
t, the running count after processing all events at or beforetequals the number of bookings withstart <= t < end. Processing ends before starts at the same time implements the half-open rule, so touching bookings are never counted together. The peak is a lower bound on rooms needed, and it is achievable by reusing any room that has been freed.
Complexity
- Time:
O(n log n)for the two sorts; the scans are linear. - Space:
O(n)for the filtered list and the event list.
Reference solution
from typing import List, Tuple
def booked_time_and_rooms(intervals: List[Tuple[int, int]]) -> Tuple[int, int]:
valid = [(s, e) for s, e in intervals if s < e]
if not valid:
return (0, 0)
ordered = sorted(valid)
covered = 0
block_start, block_end = ordered[0]
for s, e in ordered[1:]:
if s > block_end:
covered += block_end - block_start
block_start, block_end = s, e
else:
block_end = max(block_end, e)
covered += block_end - block_start
events = []
for s, e in valid:
events.append((s, 1))
events.append((e, -1))
events.sort()
active = 0
rooms = 0
for _, delta in events:
active += delta
if active > rooms:
rooms = active
return (covered, rooms)