LeetCode 928, Hard. Topics: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Graph. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 24 parametrized pytest cases, and a playground notebook:
Problem
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the i<sup>th</sup> node is directly connected to the j<sup>th</sup> node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Examples
Explanation: Removing node 0 leaves only node 1 infected, M(1) = 1. Removing node 1 leaves only node 0 infected, M(0) = 1. Both give the same M, so return the smaller index, 0.
Explanation: Removing node 0 still lets the infection reach nodes 1 and 2, M(2) = 2. Removing node 1 leaves only node 0 infected, M(0) = 1, so return 1.
Explanation: Removing node 0 lets the infection spread through the chain to nodes 1, 2 and 3, M(3) = 3. Removing node 1 leaves only node 0 infected, M(0) = 1, so return 1.
Constraints
n == graph.length
n == graph[i].length
2 <= n <= 300
graph[i][j] is 0 or 1.
graph[i][j] == graph[j][i]
graph[i][i] == 1
1 <= initial.length < n
0 <= initial[i] <= n - 1
- All the integers in
initial are unique.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026