Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0
Example 2:
Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] Output: 1
Example 3:
Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] Output: 1
Constraints:
n == graph.lengthn == graph[i].length2 <= n <= 300graph[i][j] is 0 or 1.graph[i][j] == graph[j][i]graph[i][i] == 11 <= initial.length < n0 <= initial[i] <= n - 1initial are unique.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Union-Find
[[1,1,0],[1,1,0],[0,0,1]] [0,1]
[[1,1,0],[1,1,1],[0,1,1]] [0,1]
[[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]] [0,1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #928: Minimize Malware Spread II
class UnionFind {
private final int[] p;
private final int[] size;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
public int size(int root) {
return size[root];
}
}
class Solution {
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
boolean[] s = new boolean[n];
for (int i : initial) {
s[i] = true;
}
UnionFind uf = new UnionFind(n);
for (int i = 0; i < n; ++i) {
if (!s[i]) {
for (int j = i + 1; j < n; ++j) {
if (graph[i][j] == 1 && !s[j]) {
uf.union(i, j);
}
}
}
}
Set<Integer>[] g = new Set[n];
Arrays.setAll(g, k -> new HashSet<>());
int[] cnt = new int[n];
for (int i : initial) {
for (int j = 0; j < n; ++j) {
if (!s[j] && graph[i][j] == 1) {
g[i].add(uf.find(j));
}
}
for (int root : g[i]) {
++cnt[root];
}
}
int ans = 0, mx = -1;
for (int i : initial) {
int t = 0;
for (int root : g[i]) {
if (cnt[root] == 1) {
t += uf.size(root);
}
}
if (t > mx || (t == mx && i < ans)) {
ans = i;
mx = t;
}
}
return ans;
}
}
// Accepted solution for LeetCode #928: Minimize Malware Spread II
type unionFind struct {
p, size []int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a), uf.find(b)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
return true
}
func (uf *unionFind) getSize(root int) int {
return uf.size[root]
}
func minMalwareSpread(graph [][]int, initial []int) int {
n := len(graph)
s := make([]bool, n)
for _, i := range initial {
s[i] = true
}
uf := newUnionFind(n)
for i := range graph {
if !s[i] {
for j := i + 1; j < n; j++ {
if graph[i][j] == 1 && !s[j] {
uf.union(i, j)
}
}
}
}
g := make([]map[int]bool, n)
for _, i := range initial {
g[i] = map[int]bool{}
}
cnt := make([]int, n)
for _, i := range initial {
for j := 0; j < n; j++ {
if !s[j] && graph[i][j] == 1 {
g[i][uf.find(j)] = true
}
}
for root := range g[i] {
cnt[root]++
}
}
ans, mx := 0, -1
for _, i := range initial {
t := 0
for root := range g[i] {
if cnt[root] == 1 {
t += uf.getSize(root)
}
}
if t > mx || t == mx && i < ans {
ans, mx = i, t
}
}
return ans
}
# Accepted solution for LeetCode #928: Minimize Malware Spread II
class UnionFind:
__slots__ = "p", "size"
def __init__(self, n: int):
self.p = list(range(n))
self.size = [1] * n
def find(self, x: int) -> int:
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a: int, b: int) -> bool:
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
def get_size(self, root: int) -> int:
return self.size[root]
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
n = len(graph)
s = set(initial)
uf = UnionFind(n)
for i in range(n):
if i not in s:
for j in range(i + 1, n):
graph[i][j] and j not in s and uf.union(i, j)
g = defaultdict(set)
cnt = Counter()
for i in initial:
for j in range(n):
if j not in s and graph[i][j]:
g[i].add(uf.find(j))
for root in g[i]:
cnt[root] += 1
ans, mx = 0, -1
for i in initial:
t = sum(uf.get_size(root) for root in g[i] if cnt[root] == 1)
if t > mx or (t == mx and i < ans):
ans, mx = i, t
return ans
// Accepted solution for LeetCode #928: Minimize Malware Spread II
/**
* [0928] Minimize Malware Spread II
*
* You are given a network of n nodes represented as an n x n adjacency matrix graph, where the i^th node is directly connected to the j^th 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.
*
* Example 1:
* Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
* Output: 0
* Example 2:
* Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
* Output: 1
* Example 3:
* Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
* Output: 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.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimize-malware-spread-ii/
// discuss: https://leetcode.com/problems/minimize-malware-spread-ii/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/minimize-malware-spread-ii/solutions/2651307/rust-100-faster-100-memory-dfs/
pub fn min_malware_spread(graph: Vec<Vec<i32>>, initial: Vec<i32>) -> i32 {
let initial_set: std::collections::HashSet<i32> = initial.iter().map(|i| *i).collect();
let mut visited_count: Vec<i32> = vec![0; graph.len()];
let mut result: Vec<(i32, std::collections::HashSet<i32>)> = initial
.iter()
.map(|start| {
let mut visited = std::collections::HashSet::new();
Solution::dfs_helper(
*start,
&graph,
&mut visited,
&mut visited_count,
&initial_set,
);
(-start, visited)
})
.collect();
result
.iter()
.map(|(i1, s1)| {
(
i1,
s1.iter()
.filter(|elem| visited_count[**elem as usize] == 1)
.count(),
)
})
.max_by(|(i1, t1), (i2, t2)| t1.cmp(t2).then(i1.cmp(i2)))
.map_or_else(|| 0, |res| -*res.0)
}
fn dfs_helper(
start: i32,
graph: &Vec<Vec<i32>>,
visited: &mut std::collections::HashSet<i32>,
visited_count: &mut Vec<i32>,
initial: &std::collections::HashSet<i32>,
) {
if !visited.contains(&start) {
visited.insert(start);
visited_count[start as usize] += 1;
let row = &graph[start as usize];
for (i, elem) in row.iter().enumerate() {
if *elem != 0 && !initial.contains(&(i as i32)) {
Solution::dfs_helper(i as i32, graph, visited, visited_count, initial);
}
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0928_example_1() {
let graph = vec![vec![1, 1, 0], vec![1, 1, 0], vec![0, 0, 1]];
let initial = vec![0, 1];
let result = 0;
assert_eq!(Solution::min_malware_spread(graph, initial), result);
}
#[test]
fn test_0928_example_2() {
let graph = vec![vec![1, 1, 0], vec![1, 1, 1], vec![0, 1, 1]];
let initial = vec![0, 1];
let result = 1;
assert_eq!(Solution::min_malware_spread(graph, initial), result);
}
#[test]
fn test_0928_example_3() {
let graph = vec![
vec![1, 1, 0, 0],
vec![1, 1, 1, 0],
vec![0, 1, 1, 1],
vec![0, 0, 1, 1],
];
let initial = vec![0, 1];
let result = 1;
assert_eq!(Solution::min_malware_spread(graph, initial), result);
}
}
// Accepted solution for LeetCode #928: Minimize Malware Spread II
class UnionFind {
p: number[];
size: number[];
constructor(n: number) {
this.p = Array(n)
.fill(0)
.map((_, i) => i);
this.size = Array(n).fill(1);
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
const [pa, pb] = [this.find(a), this.find(b)];
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
getSize(root: number): number {
return this.size[root];
}
}
function minMalwareSpread(graph: number[][], initial: number[]): number {
const n = graph.length;
const s = new Set(initial);
const uf = new UnionFind(n);
for (let i = 0; i < n; ++i) {
if (!s.has(i)) {
for (let j = i + 1; j < n; ++j) {
if (graph[i][j] && !s.has(j)) {
uf.union(i, j);
}
}
}
}
const g: Set<number>[] = Array.from({ length: n }, () => new Set());
const cnt: number[] = Array(n).fill(0);
for (const i of initial) {
for (let j = 0; j < n; ++j) {
if (graph[i][j] && !s.has(j)) {
g[i].add(uf.find(j));
}
}
for (const root of g[i]) {
++cnt[root];
}
}
let ans = 0;
let mx = -1;
for (const i of initial) {
let t = 0;
for (const root of g[i]) {
if (cnt[root] === 1) {
t += uf.getSize(root);
}
}
if (t > mx || (t === mx && i < ans)) {
[ans, mx] = [i, t];
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.