Skip to main content
Back to problems
#924
Hard Algorithms

Minimize malware spread

Array Hash Table Depth-First Search Breadth-First Search Union-Find Graph Theory
43.0% acceptance
Feb 25, 2026
1116
653
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. 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. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_malware_spread(graph: Vec<Vec<i32>>, initial: Vec<i32>) -> i32 {
    let n = graph.len();
    let mut parent: Vec<usize> = (0..n).collect();
    let mut size = vec![1usize; n];
    fn find(parent: &mut Vec<usize>, x: usize) -> usize {
      if parent[x] != x { parent[x] = find(parent, parent[x]); }
      parent[x]
    }
    for i in 0..n {
      for j in i+1..n {
        if graph[i][j] == 1 {
          let pi = find(&mut parent, i);
          let pj = find(&mut parent, j);
          if pi != pj {
            let si = size[pi]; let sj = size[pj];
            parent[pi] = pj;
            size[pj] = si + sj;
          }
        }
      }
    }
    let mut initial = initial.clone();
    initial.sort();
    // For each component, count how many initial nodes
    let mut comp_initial = vec![0i32; n];
    for &node in &initial {
      let p = find(&mut parent, node as usize);
      comp_initial[p] += 1;
    }
    let mut best = initial[0];
    let mut best_size = 0i32;
    for &node in &initial {
      let p = find(&mut parent, node as usize);
      let s = size[p] as i32;
      if comp_initial[p] == 1 {
        if s > best_size {
          best_size = s;
          best = node;
        }
      }
    }
    best
  }
}