Ctrl K

Which Machine to Unplug

Hard
A network of n machines is given as an adjacency matrix network: network[i][j] == 1 when machines i and j are linked directly. At the start, the machines listed in infected carry a virus. The virus travels along links: whenever one of two directly linked machines is infected, the other one gets infected too. This goes on until no one else can be infected. Before the outbreak you may unplug exactly one machine from infected completely: it disappears along with all its links and is not counted. Return the machine whose removal leads to the fewest infected machines in the end. If several choices tie, return the smallest index.
Example 1
network=[[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]], infected=[0, 2] → 2

The machines form a chain 0 — 1 — 2 — 3. Unplugging 0 lets the virus from 2 reach 1 and 3, for 3 infected. Unplugging 2 breaks the chain: from 0 only 1 gets infected, for 2 infected.

Example 2
network=[[1, 1, 1], [1, 1, 1], [1, 1, 1]], infected=[1, 0] → 0

Whichever of the two we unplug, the other one infects both remaining machines. On a tie we return the smaller index, 0.

Example 3
network=[[1, 1, 0], [1, 1, 0], [0, 0, 1]], infected=[1] → 1
Constraints
  • 2 ≤ n ≤ 1000, network is an n × n matrix of 0s and 1s
  • network[i][j] == network[j][i], network[i][i] == 1
  • 1 ≤ len(infected) < n
  • 0 ≤ infected[i] < n, all values in infected are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWhich Machine to Cure HardRooms Open from the Hall MediumGroups Linked by Shared Tags MediumOne-Swap Word Families HardSpread the News to Everyone Hard
loading Python…
Input
network=[[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]], infected=[0, 2]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 75 tests on the server, hidden ones included.