Minimum Court Allocation for Match Reservations
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A sports facility receives match reservations [start, end] spanning the day, possibly listed out of chronological order. Each court can host only one match at a time, except that back-to-back reservations where one match finishes at timestamp T and another begins at timestamp T may use the same court without conflict.
Implement assign_courts(bookings) to assign every reservation in bookings to a court ID so that:
- No two overlapping reservations are placed on the same court.
- The count of distinct courts
kopened across the entire schedule is as small as possible. - Opened courts are numbered contiguously
0, 1, ..., k - 1.
def assign_courts(bookings: List[List[int]]) -> List[int]: ...
Return an integer list assignments of length len(bookings) where assignments[i] is the court ID assigned to bookings[i]. Whenever multiple valid schedules achieve the minimum court count k, any one of them may be returned.
Examples
Example 1
bookings = [[20, 35], [10, 20], [15, 30], [30, 45]]
output = [0, 0, 1, 1]
Walk-through:
- Chronologically, bookings[1] = [10, 20] starts earliest on court 0, and bookings[2] = [15, 30] overlaps with it so it opens court 1.
- At t = 20, [10, 20] finishes just in time for bookings[0] = [20, 35] to reuse court 0.
- At t = 30, [15, 30] finishes so bookings[3] = [30, 45] reuses court 1.
Only 2 courts (0 and 1) are needed, and [0, 0, 1, 1] reports their IDs in the caller's original index order ([1, 1, 0, 0] is equally valid).
Example 2
bookings = [[0, 12], [4, 10], [8, 15], [10, 18]]
output = [0, 1, 2, 1]
Walk-through:
At t = 8, reservations [0, 12], [4, 10], and [8, 15] are all running concurrently, so at least 3 courts (0, 1, 2) are unavoidable. Once [4, 10] vacates court 1 at t = 10, [10, 18] reuses court 1.
Constraints
1 <= len(bookings) <= 10^5len(bookings[i]) == 2with integers0 <= start < end <= 10^9
Step-by-step walkthrough
Understand the reservation rules and output alignment
Each reservation
[start, end]claims one court fromstartup toend. Because a match ending at timestampTdoes not clash with a match beginning atT, each window acts as a half-open interval[start, end)(inclusive ofstart, exclusive ofend):Time: 10 15 20 25 30 35 40 45 Court 0: [--- B1 [10,20) -)[------- B0 [20,35) --------) Court 1: [------- B2 [15,30) ----)[------ B3 [30,45) -----)We have to satisfy two constraints at once:
- Fewest courts with contiguous labels: open the minimum possible count
kof courts numbered0, 1, ..., k - 1, with zero overlapping windows on any court. - Original index alignment:
bookingscan arrive out of chronological order, andassignments[i]must correspond tobookings[i]at its original positioni.
- Fewest courts with contiguous labels: open the minimum possible count
Why peak concurrency sets the lower bound
Whenever
mreservations are simultaneously active at some instantt(start <= t < end), no two of thosemmatches can share a court—forcing every valid schedule to open at leastmcourts. Consequently, ifMis the peak simultaneous overlap anywhere in the schedule, every valid assignment requiresk >= Mcourts.Because concurrency only ticks upward when a reservation begins, the peak always occurs at one of the
starttimestamps. A naive check could count active intervals at everystart:def min_courts_brute(bookings): best = 0 for start, _ in bookings: in_progress = 0 for s2, e2 in bookings: if s2 <= start < e2: in_progress += 1 best = max(best, in_progress) return bestWith
n = 10^5intervals, nested loops require10^10checks (far too slow) and still never produce per-booking court numbers. Yet this lower bound hands us our goal: if we sweep chronologically and never open a(c + 1)-th court unlesscother matches are already running at that exactstarttimestamp, our total court countkmust equalM—provably minimal!Key idea: sweep by start time and recycle vacated courts
Walk through the reservations in non-decreasing order of
start:- Before assigning a court to a match beginning at
start_time, reclaim every busy court whose prior match satisfiesend_time <= start_time. - If one or more previously opened courts are now idle, hand out one of those idle courts.
- Only when every opened court is still occupied (
end_time > start_time), allocate a brand-new courtnext_court_idand incrementnext_court_id.
Why is
next_court_idguaranteed minimal? Consider the moment the highest-numbered courtk - 1is opened:- Courts
0, 1, ..., k - 2are all occupied right then. - Every match occupying those
k - 1courts began at or beforestart_time(by start-time sweep order) and finishes strictly afterstart_time(since it was not reclaimed). - Together with the current reservation,
kintervals overlap atstart_time, provingkcourts are unavoidable!
Because
next_court_idincrements0, 1, 2, ...without gaps, the court IDs used are automatically0 .. k - 1.- Before assigning a court to a match beginning at
Preserve caller indices while sorting
Sorting
bookingsin place would scramble the original positionsi. Instead, pair eachstart_timewithorig_idxand sort those(start_time, orig_idx)tuples:n = len(bookings) # Phase 1: Pair each booking's start time with its original index so we can # sweep chronologically while still writing answers in the original input order. sorted_bookings = [] for orig_idx in range(n): start_time = bookings[orig_idx][0] sorted_bookings.append((start_time, orig_idx)) sorted_bookings.sort()Track busy and idle courts with two min-heaps
Scanning all opened courts linearly per reservation would degrade back to
O(n^2)when thousands of matches overlap. Two min-heaps (binary-tree priority queues in Python'sheapqmodule that expose their smallest element inO(1)time and push/pop inO(log k)time) keep every stepO(log k):busy_courts: min-heap of(end_time, court_id)pairs. Its rootbusy_courts[0]is always the occupied court finishing earliest. Whilebusy_courts[0][0] <= start_time, we pop it and pushcourt_idintofree_courts.free_courts: min-heap of idlecourt_idintegers, deterministically handing out the smallest idle court ID whenever multiple courts are available.
Notice
busy_courts[0][0] <= start_time: using<=rather than<allows[20, 35]to reuse the court vacated by[10, 20]att = 20.import heapq busy_courts = [] free_courts = [] next_court_id = 0 assignments = [0] * n for start_time, orig_idx in sorted_bookings: end_time = bookings[orig_idx][1] # Use <= (not <) because a match ending at T frees its court for a match starting at T. while busy_courts and busy_courts[0][0] <= start_time: finished_end, freed_court = heapq.heappop(busy_courts) heapq.heappush(free_courts, freed_court) # Reuse an idle court if one is available; otherwise open the next contiguous court ID. if free_courts: court_id = heapq.heappop(free_courts) else: court_id = next_court_id next_court_id += 1 assignments[orig_idx] = court_id heapq.heappush(busy_courts, (end_time, court_id))Walk through Example 1 step by step
Let's trace
bookings = [[20, 35], [10, 20], [15, 30], [30, 45]]:Sorted tuples: [(10, idx=1), (15, idx=2), (20, idx=0), (30, idx=3)] orig_idx window start reclaimed (end <= start) free_courts assigned busy_courts after 1 [10, 20] 10 none [] new -> 0 [(20, 0)] 2 [15, 30] 15 none (20 > 15) [] new -> 1 [(20, 0), (30, 1)] 0 [20, 35] 20 pop (20, 0) [0] reuse 0 [(30, 1), (35, 0)] 3 [30, 45] 30 pop (30, 1) [1] reuse 1 [(35, 0), (45, 1)]Writing each court ID into
assignments[orig_idx]producesassignments = [0, 0, 1, 1]usingnext_court_id = 2courts (0and1).Complete solution
from typing import List import heapq def assign_courts(bookings: List[List[int]]) -> List[int]: """Assign every booking to a court using the minimum number of courts.""" n = len(bookings) # Phase 1: Pair each booking's start time with its original index so we can # sweep chronologically while still writing answers in the original input order. sorted_bookings = [] for orig_idx in range(n): start_time = bookings[orig_idx][0] sorted_bookings.append((start_time, orig_idx)) sorted_bookings.sort() # busy_courts: min-heap of (end_time, court_id) ordered by earliest match finish. busy_courts = [] # free_courts: min-heap of idle court_id ints so we deterministically reuse the lowest ID. free_courts = [] next_court_id = 0 assignments = [0] * n # Phase 2: Sweep bookings in ascending start-time order. for start_time, orig_idx in sorted_bookings: end_time = bookings[orig_idx][1] # Use <= (not <) because a match ending at T frees its court for a match starting at T. while busy_courts and busy_courts[0][0] <= start_time: finished_end, freed_court = heapq.heappop(busy_courts) heapq.heappush(free_courts, freed_court) # Reuse an idle court if one is available; otherwise open the next contiguous court ID. if free_courts: court_id = heapq.heappop(free_courts) else: court_id = next_court_id next_court_id += 1 assignments[orig_idx] = court_id heapq.heappush(busy_courts, (end_time, court_id)) return assignments✅ Submit now — all tests should pass.
Intuition & how it works
Picture a club desk clerk handing out numbered court passes (0, 1, 2, ...) from a pegboard as matches start in chronological order. Whenever players finish a match, they hang their pass back on the board; when the next match starts, the clerk hands out the lowest-numbered free pass on the board and only unlocks a brand-new court when the pegboard is completely empty. This greedy algorithm (making an immediate locally optimal choice at each step without backtracking) never opens a new court unless every existing court is actively hosting an overlapping match at that moment, guaranteeing that the total number of courts opened equals the busiest instant of the day.
Why do simpler approaches fall short? Scanning a plain list of open courts for every reservation takes O(n^2) time (10^10 checks at n = 10^5) and times out. Conversely, sweeping +1 / -1 start and end markers finds the peak court count k in O(n log n) time, but never assigns concrete court IDs to individual reservations. Maintaining two min-heaps (priority queues exposing their minimum item in O(1) time and updating in O(log k) time)—one keyed by earliest finish time for occupied courts and one keyed by court ID for idle courts—assigns every reservation in O(n log n) time.
Let's trace Example 1 bookings = [[20, 35], [10, 20], [15, 30], [30, 45]]:
- Pairing start times with original indices and sorting gives
(10, idx=1),(15, idx=2),(20, idx=0),(30, idx=3). [10, 20](idx=1): no courts exist yet, so open Court0;busy_courts = [(20, 0)],assignments[1] = 0.[15, 30](idx=2): earliest busy finish is20 > 15, so open Court1;busy_courts = [(20, 0), (30, 1)],assignments[2] = 1.[20, 35](idx=0):20 <= 20, so(20, 0)pops intofree_courts = [0]; reuse Court0;assignments[0] = 0.[30, 45](idx=3):30 <= 30, so(30, 1)pops intofree_courts = [1]; reuse Court1;assignments[3] = 1, returning[0, 0, 1, 1].
Complexity
- Time:
O(n log n). Building and sorting then(start_time, orig_idx)tuples takesO(n log n)time. Across the chronological sweep, each of thenreservations enters and leavesbusy_courtsat most once andfree_courtsat most once; with at mostk <= ncourts in either heap, every heap push or pop runs inO(log k) <= O(log n)time. - Space:
O(n). We allocaten(start_time, orig_idx)tuples, theassignmentslist of lengthn, and at mostk <= nheap entries.
Edge cases
- Back-to-back reservations (
[10, 20]and[20, 35]): Modeling windows as half-open intervals[start, end)(inclusive ofstart, exclusive ofend) and reclaiming viabusy_courts[0][0] <= start_timelets[20, 35]reuse[10, 20]'s court. - Out-of-order input: Writing to
assignments[orig_idx]rather than appending in sorted order preserves alignment with the caller's list. - Identical reservations (
[[4, 9], [4, 9], [4, 9]]): None vacates byt = 4, so they cleanly claim distinct courts0, 1, 2. - Single reservation (
[[0, 10^9]]): Claims Court0and returns[0]. - Timestamps up to
10^9: Comparing integer endpoints directly avoids allocating any array proportional to timestamp magnitude.
Common mistakes
- Using
<instead of<=when reclaiming courts: Writingbusy_courts[0][0] < start_timefalsely treats[10, 20]and[20, 35]as conflicting and opens extra courts. - Sorting
bookingsin place without tracking original indices: Returning sorted-order IDs[0, 1, 0, 1]on[[20, 35], [10, 20], [15, 30], [30, 45]]scrambles which reservation gets which court (bookings[0]andbookings[1]would both be assigned conflicting or wrong slots). - Using
len(busy_courts)as the assigned court ID instead of storing freed IDs: On[[0, 5], [1, 10], [5, 8]],[0, 5]takes0and[1, 10]takes1; att = 5, popping(5, 0)dropslen(busy_courts)to1, so assigninglen(busy_courts)hands Court1to[5, 8]while[1, 10]is still occupying Court1! - Allocating a timeline array of size
max(end): With coordinates up to10^9, indexing by timestamp exhausts memory immediately.
Follow-up questions
- How do you modify the algorithm when every court needs a mandatory 15-minute turnaround buffer after each match? A reservation
[start, end]now blocks its court untilend + 15, so push(end_time + 15, court_id)ontobusy_courtsinstead of(end_time, court_id). That reduces the problem to standard interval coloring on[start, end + 15), keeping the two-heap sweepO(n log n)and provably minimal (for instance,[[0, 60], [60, 120]]now requires2courts because turnaround lasts until75, whereas[[0, 60], [75, 120]]shares1court). - How does your scheduling strategy change if reservations can request specific surfaces such as grass or hard court? When every reservation specifies strictly one surface (
"grass"or"hard"), the two surface pools never interact: split the input by surface, runassign_courtsseparately on each pool inO(n log n)total time, and shift hard-court IDs byk_grass. If flexible"any"reservations mix with dedicated surface requests under fixed grass/hard court counts, naive start-time greedy can strand a later"grass"-only match if an earlier"any"match took the last grass court while a hard court sat idle; break same-start ties in favor of single-surface requests, and in offline scheduling allow reassigning an active"any"match to a concurrently free court of the other surface (or solve bounded capacity feasibility via max-flow / integer programming). - How would you handle reservations arriving dynamically one by one instead of all up front, and what optimality trade-offs arise? If walk-in matches arrive in chronological
start_timeorder, our exact two-heap sweep already runs online inO(log k)per arrival and achieves the offline optimum. If players book future windows in arbitrary arrival order and expect an immediate fixed court number, no online algorithm can always match the offline minimum (for example, arrivals[0, 4],[8, 12],[2, 6],[5, 10]force First-Fit onto3courts even though{[0, 4], [5, 10]}and{[2, 6], [8, 12]}fit on2). Production booking engines avoid that penalty by validating aggregate capacity at reservation time (using a segment tree—a balanced tree over time intervals supporting range-add and max-overlap queries inO(log T)—to confirm peak concurrency stays within total courts) while assigning concrete court numbers shortly before play using the offlineO(n log n)sweep.
Follow-up questions
- How do you modify the algorithm when every court needs a mandatory 15-minute turnaround buffer after each match?
- How does your scheduling strategy change if reservations can request specific surfaces such as grass or hard court?
- How would you handle reservations arriving dynamically one by one instead of all up front, and what optimality trade-offs arise?
Similar questions
- Minimum Tennis Courts for Concurrent Reservations
- Fixed-Window Moving Average Over a Numeric Stream
- Reciprocal-Depth Sum of Nested Lists
- Sliding-Window Mean Over an Integer Stream
- Segment-Trie Path Router with Single-Segment Wildcards
- Constant-Time LRU Store with Stream Mean
More Atlassian interview questions
- Per-User Rolling-Window Rate Limiter Medium
- Merge Overlapping Intervals Medium
- Two-by-Three React Feed Grid: Static Data, API Fetch, and Hooks Hard Pro
- Design a Trending Workspace Content Leaderboard Medium Pro
- Frontend Architecture for Live Search Over an Unbounded Catalog Hard Pro
- Music Playback State Machine with Queue, Loop, and Shuffle Medium Pro
- Distributed API Rate Limiter Architecture Easy Pro
- Post Comments and Notification Architecture Medium Pro
- Multi-Tenant Tagging Service and REST API Medium Pro
- Hybrid RBAC and Resource ACL Authorization Service Medium Pro