Two-Choice Clinic Booking: Can Everyone Get a Slot?
Trees & GraphsAuto-graded · 23 test casesLast updated
Decide whether each patient can get one of their two acceptable slots with no slot reused, by modelling slots as graph vertices and patients as edges.
Two-Choice Clinic Booking
A clinic offers appointment slots numbered 1 through num_slots. There are N patients, indexed 0 to N - 1. Patient i can only be booked into one of two slots: first_choice[i] or second_choice[i].
Assign every patient to exactly one slot, chosen from that patient's own two options, so that no slot is assigned to more than one patient. Slots may remain unused.
Return True if such an assignment exists for all patients at once, and False otherwise.
Rules and edge cases
- If
first_choice[i] == second_choice[i], patientihas only that one acceptable slot. - Different patients may have identical pairs of options, in any order. The pair
(x, y)is the same set of options as(y, x). - Every patient must receive a slot. A single patient who cannot be placed makes the answer
False. - Only the existence of a valid assignment matters. You do not return the assignment itself.
- If there are no patients (
N = 0), the answer isTrue. - If there are more patients than slots (
N > num_slots), the answer isFalse. - The function returns a Python boolean (
TrueorFalse).
Input
first_choice: list ofNintegers, the first acceptable slot of each patient.second_choice: list ofNintegers, the second acceptable slot of each patient.num_slots: integerS, the number of slots.
Output
A boolean: True if every patient can be given a distinct slot from their own two options, otherwise False.
Constraints
0 <= N <= 100000(inputs withN = 0are valid and giveTrue).1 <= num_slots <= 100000first_choiceandsecond_choiceboth have lengthN.- Every value in both lists is an integer between
1andnum_slotsinclusive. - The solution should run in near-linear time. Deep recursion may overflow the stack on large inputs.
Examples
Example 1
Input: can_assign_slots([1, 2, 3], [2, 3, 1], 3)
Output: True
Example 2
Input: can_assign_slots([1, 1], [1, 2], 2)
Output: True
Example 3
Input: can_assign_slots([1, 1, 2], [1, 2, 2], 2)
Output: False
Hints
Hint 1
Think of each slot as a node and each patient as a connection between their two acceptable slots. What does assigning a patient to a slot mean in that picture?
Hint 2
A group of connected slots can only serve the patients whose connections lie inside that group. Compare the number of patients with the number of slots in each group.
Hint 3
A group works exactly when its patients do not outnumber its slots. Track slot count and patient count per group with a union-find structure, and use an iterative find to avoid deep recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a graph where each slot is a vertex and each patient is an edge joining their two acceptable slots. If both options are the same slot, the edge is a self-loop. Giving a patient a slot means pointing their edge at one of its endpoints, and each vertex may be pointed at by at most one edge.
Edges can only be assigned to vertices in their own connected component, so components are independent. The answer is True exactly when every connected component has at most as many edges as vertices.
Why it is correct
- Necessity: if a component has more edges (patients) than vertices (slots), the pigeonhole principle forces two patients onto the same slot.
- Sufficiency: a connected component with
E <= Vis either a tree (E = V - 1) or has exactly one cycle (E = V), where a self-loop counts as a cycle.- For a tree, root it anywhere and point each edge at its child endpoint. Every non-root vertex gets exactly one edge.
- For a unicyclic component, orient the cycle edges around the cycle so each cycle vertex gets one, then orient every hanging tree edge away from the cycle.
A greedy pass that gives each patient their first free choice is wrong, because it can block a later patient who has no alternative.
Implementation
Use union-find. Each root stores its vertex count and edge count. Slots that no patient mentions never affect the result, so they are created lazily.
- With no patients, return
True. WithN > num_slots, returnFalseimmediately. - If a patient's two slots are already in the same component (including a self-loop), increase that component's edge count by one. If edges exceed vertices, return
False. - Otherwise merge the two components, adding their vertex counts and edge counts, plus one for the new edge. Check the same condition.
The find function is iterative with path compression, so there is no recursion-depth problem at 100,000 slots.
Complexity
- Time:
O((N + S) * alpha(S)), close to linear. - Space:
O(N)for the lazily created union-find entries.
Reference solution
from typing import List
def can_assign_slots(first_choice: List[int], second_choice: List[int], num_slots: int) -> bool:
n = len(first_choice)
if n == 0:
return True
if n > num_slots:
return False
parent = {}
verts = {}
edges = {}
def find(x: int) -> int:
if x not in parent:
parent[x] = x
verts[x] = 1
edges[x] = 0
return x
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
parent[x], x = root, parent[x]
return root
for a, b in zip(first_choice, second_choice):
ra, rb = find(a), find(b)
if ra == rb:
edges[ra] += 1
if edges[ra] > verts[ra]:
return False
else:
if verts[ra] < verts[rb]:
ra, rb = rb, ra
parent[rb] = ra
verts[ra] += verts[rb]
edges[ra] += edges[rb] + 1
if edges[ra] > verts[ra]:
return False
return True