Bank app~25 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-785bfs
A bank reviews large transfers under the four-eyes rule. Two analysts who worked on the same case must sit in different review teams, the north team and the south team.
Analysts are numbered from 0. Some are already assigned to a team, and the others are free to go in either.
Write can_split(n, conflicts, pinned).
n analysts, numbered from 0 to n - 1.conflicts[i] is [a, b]: analysts a and b worked on the same case, so they must be in different teams. The same pair may appear twice, and a is never b.pinned[i] is 1 when analyst i must be in the north team, 2 for the south team, and 0 when the analyst is free.true when every analyst can be given a team so that all conflicts and all pins hold, and false otherwise.Input: n = 6, conflicts = [[0,1],[1,2],[2,3],[4,5]], pinned = [0,0,2,0,1,0]
Output: trueA search colours each group of linked analysts from its first analyst, who goes in team 0 (north). A pin says whether the whole group must keep that colouring or flip it.
| Group | Colouring from the first analyst | Pinned analyst | Needs | Result |
|---|---|---|---|---|
| 0, 1, 2, 3 | 0 north, 1 south, 2 north, 3 south | analyst 2 wants south | flip | fine |
| 4, 5 | 4 north, 5 south | analyst 4 wants north | keep | fine |
Each group has a single flip rule that all its pins agree on, so the answer is true.
Input: n = 3, conflicts = [[0,1],[1,2],[2,0]], pinned = [0,0,0]
Output: falseThree analysts in a loop of conflicts cannot split into two teams.
Input: n = 3, conflicts = [[0,1],[1,2]], pinned = [1,0,2]
Output: falseAnalysts 0 and 2 must be in the same team, because both differ from analyst 1. But one is pinned north and the other south.
1 ≤ n ≤ 100,0000 ≤ conflicts.length ≤ 100,000, and each conflict is [a, b] with 0 ≤ a, b < n and a ≠ bpinned.length = n, and every entry is 0, 1 or 2Trying every assignment of n analysts to two teams means 2^n assignments, which is far beyond reach for n = 100,000. In a group of linked analysts, one analyst's team fixes every other team in the group. So one search per group, costing O(n + m) in all, decides everything.