KatInterview

Two-Choice Clinic Booking: Can Everyone Get a Slot?

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsunion-findgraph-modelingmatching

Last 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], patient i has 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 is True.
  • If there are more patients than slots (N > num_slots), the answer is False.
  • The function returns a Python boolean (True or False).

Input

  • first_choice: list of N integers, the first acceptable slot of each patient.
  • second_choice: list of N integers, the second acceptable slot of each patient.
  • num_slots: integer S, 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 with N = 0 are valid and give True).
  • 1 <= num_slots <= 100000
  • first_choice and second_choice both have length N.
  • Every value in both lists is an integer between 1 and num_slots inclusive.
  • 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.