You are given a list preferences where preferences[i] = [a, b] holds the two preferred time slot indices of the i-th patient. Each time slot can hold at most one patient.
Determine whether it is possible to assign every patient to one of their two preferred slots so that no two patients are assigned to the same slot. Return True if such an assignment exists, otherwise return False.
Function Signature
def can_schedule_all(preferences: list[list[int]]) -> bool:
Rules
-
Patient
i
must get exactly one of
preferences[i][0]
and
preferences[i][1]
.
-
Two or more patients may list the same pair of slots.
-
Slots that no patient lists play no part in the answer.
Constraints
-
1 <= len(preferences) <= 500
-
len(preferences[i]) == 2
-
0 <= preferences[i][0], preferences[i][1] <= 1000
-
preferences[i][0] != preferences[i][1]
Examples
Example 1
Input: preferences = [[0,1],[0,2],[1,2]]
Output: True
Assign patient 0 to slot 0, patient 1 to slot 2 and patient 2 to slot 1. Every patient gets one of their own two slots and no slot is used twice.
Example 2
Input: preferences = [[0,1],[0,1],[0,1]]
Output: False
All three patients accept only slots 0 and 1. Two slots cannot hold three patients, so one patient is left out.
Example 3
Input: preferences = [[0,1],[1,2],[2,0],[2,1],[4,5]]
Output: False
Patients 0 to 3 only accept slots 0, 1 and 2, so four patients compete for three slots. The five distinct slots overall do not help, because slots 4 and 5 are open only to patient 4.