You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth 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.

Input & Output

Example 1 — Basic Connected Graph
$ Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
💡 Note: Nodes 0 and 1 are connected and initially infected. Node 2 is isolated. If we remove node 0, only node 1 remains infected. If we remove node 1, only node 0 remains infected. Both removals result in 1 infected node, so return the smaller index 0.
Example 2 — Chain Connection
$ Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1
💡 Note: Initial nodes 0,1 are connected. If we remove node 0, the malware spreads from node 1 to nodes 2,3 (total 3 infected). If we remove node 1, only node 0 remains infected (total 1 infected). Removing node 1 minimizes infections.
Example 3 — Multiple Components
$ Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
💡 Note: All nodes are isolated. Removing either node 0 or 2 results in 1 infected node. Return the smaller index 0.

Constraints

  • n == graph.length == graph[i].length
  • 2 ≤ n ≤ 300
  • graph[i][j] is 0 or 1
  • graph[i][i] == 1
  • 1 ≤ initial.length < n
  • 0 ≤ initial[i] ≤ n - 1
  • All integers in initial are unique

Visualization

Tap to expand
Minimize Malware Spread by Strategic RemovalNode 0Node 1Node 2Initially Infected: [0,1]↓ Try Removing Each ↓Remove 0 → 1 infectedRemove 1 → 1 infectedResult: Remove node 0 (smallest index with minimum infections)
Understanding the Visualization
1
Input Graph
Network with connections and initially infected nodes [0,1]
2
Analyze Removal Impact
Test removing each infected node to see spread reduction
3
Choose Optimal
Select node whose removal minimizes total infections
Key Takeaway
🎯 Key Insight: Remove the infected node that uniquely threatens the largest clean component
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen