HardArrayHash TableDepth-First SearchBreadth-First SearchUnion FindGraphUpdated Sep 2026

928. Minimize Malware Spread II

Asked at Visa

Difficulty

Hard

Time

O(k * n^2)

Space

O(n)

Pattern

Array

Companies

1

Problem

You are given a network of n nodes as an n x n adjacency matrix graph. graph[i][j] == 1 means node i and node j are directly connected. Some nodes in the list initial already carry malware.

Malware spreads like this: if two nodes are directly connected and at least one of them is infected, then both become infected. This repeats until nothing new can be infected. Let M(initial) be the total number of infected nodes when the spread stops.

You must remove exactly one node from initial. Removing it deletes the node and every connection it has, so it can no longer be infected and can no longer pass malware along. Return the node whose removal makes M(initial) as small as possible. If several nodes give the same smallest number, return the one with the smallest index.

Removing one infected node cuts its edges

graph012301231100111001110011Nodes 0 and 1 start infected (red); the matrix showsthe path 0-1-2-3nodes01230123We try removing node 1 and all of its edges
In a path 0-1-2-3 with initial [0,1], removing node 1 blocks the spread from 0 to the rest, so only 1 node stays infected.

Constraints

  • ●2 <= n <= 300
  • ●n == graph.length == graph[i].length
  • ●graph[i][j] is 0 or 1
  • ●graph[i][j] == graph[j][i] (the graph is undirected)
  • ●graph[i][i] == 1
  • ●1 <= initial.length < n
  • ●0 <= initial[i] <= n - 1
  • ●All values in initial are unique

Examples

Example 1
Inputgraph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output0
WhyNodes 0 and 1 are connected; node 2 is alone. Remove 0: only node 1 is infected (node 2 is never reached), so 1 node. Remove 1: only node 0 is infected, again 1 node. Same count, so we pick the smaller index, 0.
Example 2
Inputgraph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output1
WhyThe graph is a path 0-1-2. Remove 0: node 1 stays infected and spreads to node 2, giving 2 infected nodes. Remove 1: node 0 is infected but its only link was to 1, which is gone, so only 1 node is infected. Removing 1 is better.
Example 3
Inputgraph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output1
WhyThe graph is a path 0-1-2-3. Remove 0: node 1 is infected and spreads to 2 and then 3, so 3 nodes. Remove 1: node 0 is infected alone, so 1 node. Removing 1 wins.

Asked At

1 companies
CompanyDifficulty
VisaHardView all Visa questions →

How to Think About It

1

Unlike version I, removing the node cuts its edges, so it can also block the spread from other infected nodes that would have passed through it.

2

Straightforward approach: for each candidate in initial, pretend it is removed and run a BFS from every other initial node, never entering the removed node. Count infected nodes. With n <= 300 this is O(k * n²), which is acceptable.

3

Smarter approach: for each clean (non-initial) node, find which initial nodes can reach it without passing through another initial node. If exactly one initial node reaches it, removing that initial node saves it. Sum the saved counts per initial node and pick the max.

4

Tie-breaking: sort initial first and only replace the best answer when the infected count is strictly smaller.

5

Walkthrough: graph 0-1 connected, 2 isolated, initial [0,1]. Removing 0: 1 still infects only itself -> 1 infected. Removing 1: 0 infects itself -> 1. Tie -> return 0.

Optimal Approach

Step 1: Sort initial; best, bestCount = initial[0], infinity.
Step 2: For each rem in initial:
BFS from every other initial node, skipping rem, over the adjacency matrix.
Let cnt be the number of infected nodes.
If cnt < bestCount: update best and bestCount.
Step 3: Return best.

Time: O(k * n²) where k = len(initial). Space: O(n).

Try each candidate, then BFS

sort initialpick remBFS, skip remkeep smaller countThe outer loop walks over each candidate in sortedordernodes01230123Remove 1: node 0 is infected, but 2 and 3 stay clean,so count = 1remove rem → BFS from other initial nodescnt = number of visited nodeskeep rem with the smallest cnttie → smallest index
For every node in initial we delete it, run BFS from the remaining infected nodes, and keep the candidate with the fewest infected nodes.
ComplexityTime O(k * n^2)Space O(n)k is the number of initially infected nodes; for each candidate we scan the whole adjacency matrix once with BFS, and the queue and visited array use O(n) memory.

What Trips People Up in Real Interviews

1

Reusing the version I solution (component sizes). Here removal cuts edges, which changes the components themselves.

2

Counting the removed node as infected. It is removed from the network entirely.

3

Breaking ties by input order. The smallest index must win — sort initial or compare explicitly.

4

Forgetting that the adjacency matrix has 1s on the diagonal; the seen check handles it.

Solution Code

O(k * n^2) time
from collections import deque

def minMalwareSpread(graph, initial):
    n = len(graph)
    initial = sorted(initial)
    best, best_count = initial[0], float('inf')
    for rem in initial:
        seen = [False] * n
        seen[rem] = True
        q = deque()
        for s in initial:
            if s != rem:
                seen[s] = True
                q.append(s)
        cnt = len(q)
        while q:
            u = q.popleft()
            for v in range(n):
                if graph[u][v] and not seen[v]:
                    seen[v] = True
                    cnt += 1
                    q.append(v)
        if cnt < best_count:
            best, best_count = rem, cnt
    return best

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Minimize Malware Spread II problem?

Minimize Malware Spread II gives you a network (as an adjacency matrix) and a list of initially infected nodes. You may completely remove one infected node — along with all its connections — before malware spreads. Which node should you remove to minimize the final number of infected nodes? Ties go to the smallest index.

How do you solve Minimize Malware Spread II?

The optimal approach runs in O(k * n^2) time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Minimize Malware Spread II?

Minimize Malware Spread II is asked at Visa. It is a hard difficulty problem.

What are common mistakes on Minimize Malware Spread II?
  • Reusing the version I solution (component sizes). Here removal cuts edges, which changes the components themselves.
  • Counting the removed node as infected. It is removed from the network entirely.
  • Breaking ties by input order. The smallest index must win — sort `initial` or compare explicitly.
  • Forgetting that the adjacency matrix has 1s on the diagonal; the `seen` check handles it.