Engineering platform~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-785bfs
You work on the deploy tool of an engineering platform. It restarts n services in two waves, one wave after the other.
Two services that call each other must never restart in the same wave, so one of them is always running. Services are numbered 0 to n - 1. A link joins two services that call each other.
Some services have no links at all, and the services may form several separate groups. Before the deploy starts, the tool must check whether any split into two waves can follow the rule.
Write can_split(n, links).
n is the number of services.links[i] = [a, b] means services a and b call each other, with a ≠ b.true when every service can be put in wave 1 or wave 2 so that no link joins two services of the same wave.Input: n = 5, links = [[0, 1], [0, 3], [1, 2], [2, 3], [3, 4]]
Output: truePut service 0 in wave 0. Every linked service goes in the other wave, and each one is checked against its own links when it is taken from the queue.
| Step | Take | Queue after | Waves of 0 to 4 (- is not placed) |
|---|---|---|---|
| 1 | 0 | 1, 3 | 0, 1, -, 1, - |
| 2 | 1 | 3, 2 | 0, 1, 0, 1, - |
| 3 | 3 | 2, 4 | 0, 1, 0, 1, 0 |
| 4 | 2 | 4 | 0, 1, 0, 1, 0 |
| 5 | 4 | 0, 1, 0, 1, 0 |
No link joins two services of one wave.
Input: n = 3, links = [[0, 1], [1, 2], [2, 0]]
Output: falseThree services that all call each other. Any two of them share a wave, whichever way you place them.
Input: n = 5, links = [[0, 1], [2, 3]]
Output: trueTwo separate pairs, and service 4 with no links. Each part can be placed on its own.
1 ≤ n ≤ 100,0000 ≤ len(links) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < n and a ≠ bThere can be 100,000 services. Trying every way to give each one a wave is 2^n choices. Even a repeating scan over the links costs n × m, about 10 billion steps on a long chain. The answer must place each service once and look at each link a few times: n + m.