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:

  1. No two overlapping reservations are placed on the same court.
  2. The count of distinct courts k opened across the entire schedule is as small as possible.
  3. 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^5
  • len(bookings[i]) == 2 with integers 0 <= start < end <= 10^9

Step-by-step walkthrough

  1. Understand the reservation rules and output alignment

    Each reservation [start, end] claims one court from start up to end. Because a match ending at timestamp T does not clash with a match beginning at T, each window acts as a half-open interval [start, end) (inclusive of start, exclusive of end):

    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:

    1. Fewest courts with contiguous labels: open the minimum possible count k of courts numbered 0, 1, ..., k - 1, with zero overlapping windows on any court.
    2. Original index alignment: bookings can arrive out of chronological order, and assignments[i] must correspond to bookings[i] at its original position i.
  2. Why peak concurrency sets the lower bound

    Whenever m reservations are simultaneously active at some instant t (start <= t < end), no two of those m matches can share a court—forcing every valid schedule to open at least m courts. Consequently, if M is the peak simultaneous overlap anywhere in the schedule, every valid assignment requires k >= M courts.

    Because concurrency only ticks upward when a reservation begins, the peak always occurs at one of the start timestamps. A naive check could count active intervals at every start:

    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 best
    

    With n = 10^5 intervals, nested loops require 10^10 checks (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 unless c other matches are already running at that exact start timestamp, our total court count k must equal M—provably minimal!

  3. Key idea: sweep by start time and recycle vacated courts

    Walk through the reservations in non-decreasing order of start:

    1. Before assigning a court to a match beginning at start_time, reclaim every busy court whose prior match satisfies end_time <= start_time.
    2. If one or more previously opened courts are now idle, hand out one of those idle courts.
    3. Only when every opened court is still occupied (end_time > start_time), allocate a brand-new court next_court_id and increment next_court_id.

    Why is next_court_id guaranteed minimal? Consider the moment the highest-numbered court k - 1 is opened:

    • Courts 0, 1, ..., k - 2 are all occupied right then.
    • Every match occupying those k - 1 courts began at or before start_time (by start-time sweep order) and finishes strictly after start_time (since it was not reclaimed).
    • Together with the current reservation, k intervals overlap at start_time, proving k courts are unavoidable!

    Because next_court_id increments 0, 1, 2, ... without gaps, the court IDs used are automatically 0 .. k - 1.

  4. Preserve caller indices while sorting

    Sorting bookings in place would scramble the original positions i. Instead, pair each start_time with orig_idx and 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()
    
  5. 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's heapq module that expose their smallest element in O(1) time and push/pop in O(log k) time) keep every step O(log k):

    • busy_courts: min-heap of (end_time, court_id) pairs. Its root busy_courts[0] is always the occupied court finishing earliest. While busy_courts[0][0] <= start_time, we pop it and push court_id into free_courts.
    • free_courts: min-heap of idle court_id integers, 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] at t = 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))
    
  6. 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] produces assignments = [0, 0, 1, 1] using next_court_id = 2 courts (0 and 1).

  7. 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]]:

  1. Pairing start times with original indices and sorting gives (10, idx=1), (15, idx=2), (20, idx=0), (30, idx=3).
  2. [10, 20] (idx=1): no courts exist yet, so open Court 0; busy_courts = [(20, 0)], assignments[1] = 0.
  3. [15, 30] (idx=2): earliest busy finish is 20 > 15, so open Court 1; busy_courts = [(20, 0), (30, 1)], assignments[2] = 1.
  4. [20, 35] (idx=0): 20 <= 20, so (20, 0) pops into free_courts = [0]; reuse Court 0; assignments[0] = 0.
  5. [30, 45] (idx=3): 30 <= 30, so (30, 1) pops into free_courts = [1]; reuse Court 1; assignments[3] = 1, returning [0, 0, 1, 1].

Complexity

  • Time: O(n log n). Building and sorting the n (start_time, orig_idx) tuples takes O(n log n) time. Across the chronological sweep, each of the n reservations enters and leaves busy_courts at most once and free_courts at most once; with at most k <= n courts in either heap, every heap push or pop runs in O(log k) <= O(log n) time.
  • Space: O(n). We allocate n (start_time, orig_idx) tuples, the assignments list of length n, and at most k <= n heap entries.

Edge cases

  • Back-to-back reservations ([10, 20] and [20, 35]): Modeling windows as half-open intervals [start, end) (inclusive of start, exclusive of end) and reclaiming via busy_courts[0][0] <= start_time lets [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 by t = 4, so they cleanly claim distinct courts 0, 1, 2.
  • Single reservation ([[0, 10^9]]): Claims Court 0 and 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: Writing busy_courts[0][0] < start_time falsely treats [10, 20] and [20, 35] as conflicting and opens extra courts.
  • Sorting bookings in 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] and bookings[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] takes 0 and [1, 10] takes 1; at t = 5, popping (5, 0) drops len(busy_courts) to 1, so assigning len(busy_courts) hands Court 1 to [5, 8] while [1, 10] is still occupying Court 1!
  • Allocating a timeline array of size max(end): With coordinates up to 10^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 until end + 15, so push (end_time + 15, court_id) onto busy_courts instead of (end_time, court_id). That reduces the problem to standard interval coloring on [start, end + 15), keeping the two-heap sweep O(n log n) and provably minimal (for instance, [[0, 60], [60, 120]] now requires 2 courts because turnaround lasts until 75, whereas [[0, 60], [75, 120]] shares 1 court).
  • 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, run assign_courts separately on each pool in O(n log n) total time, and shift hard-court IDs by k_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_time order, our exact two-heap sweep already runs online in O(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 onto 3 courts even though {[0, 4], [5, 10]} and {[2, 6], [8, 12]} fit on 2). 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 in O(log T)—to confirm peak concurrency stays within total courts) while assigning concrete court numbers shortly before play using the offline O(n log n) sweep.

Follow-up questions

Similar questions

More Atlassian interview questions

All 55 Atlassian questions →