964. Minimize Malware Spread II
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find a node in an initially infected set (initial) that, upon removal from the network, minimizes the total number of infected nodes after the malware spreads. The removal of a node also removes all its connections. If multiple nodes yield the same minimal infection size, we should choose the one with the smallest index.
Solution
Minimize Malware Spread II in Python
import collections
class Solution:
def minMalwareSpread(self, graph: list[list[int]], initial: list[int]) -> int:
n = len(graph)
# Sort initial to handle the tie-breaking rule (smallest index first).
initial.sort()
min_infected = n + 1 # More than any possible infected count
result_node = -1
# Iterate through each node in `initial` to consider removing it.
for node_to_remove in initial:
# Set up the initial sources for this simulation.
q = collections.deque()
visited = [False] * n
for i in initial:
if i != node_to_remove:
q.append(i)
visited[i] = True
# The number of infected nodes starts with the number of initial sources.
current_infected = len(q)
# Perform a multi-source BFS.
while q:
u = q.popleft()
for v in range(n):
# The removed node cannot be part of the graph.
if v == node_to_remove:
continue
# If there's an edge and the neighbor is not yet infected (visited).
if graph[u][v] == 1 and not visited[v]:
visited[v] = True
current_infected += 1
q.append(v)
# Check if this removal is better.
if current_infected < min_infected:
min_infected = current_infected
result_node = node_to_remove
# Because `initial` is sorted, the first node that achieves the minimum
# will be the one with the smallest index. So we don't need to handle
# the `current_infected == min_infected` case.
return result_node
Minimize Malware Spread II in Java
class Solution {
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
// Sort initial to handle the tie-breaking rule (smallest index first).
Arrays.sort(initial);
int minInfected = n + 1; // More than any possible infected count
int resultNode = -1;
// Iterate through each node in `initial` to consider removing it.
for (int nodeToRemove : initial) {
boolean[] visited = new boolean[n];
Queue<Integer> queue = new LinkedList<>();
// Set up the initial sources for this simulation.
for (int i : initial) {
if (i != nodeToRemove) {
queue.offer(i);
visited[i] = true;
}
}
// The number of infected nodes starts with the number of initial sources.
int currentInfected = queue.size();
// Perform a multi-source BFS.
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v = 0; v < n; v++) {
// The removed node cannot be part of the graph.
if (v == nodeToRemove) {
continue;
}
// If there's an edge and the neighbor is not yet infected (visited).
if (graph[u][v] == 1 && !visited[v]) {
visited[v] = true;
currentInfected++;
queue.offer(v);
}
}
}
// Check if this removal is better.
if (currentInfected < minInfected) {
minInfected = currentInfected;
resultNode = nodeToRemove;
}
// Because `initial` is sorted, the first node that achieves the minimum
// will be the one with the smallest index. So we don't need to handle
// the `currentInfected == minInfected` case.
}
return resultNode;
}
}
Minimize Malware Spread II in C++
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int n = graph.size();
// Sort initial to handle the tie-breaking rule (smallest index first).
sort(initial.begin(), initial.end());
int min_infected = n + 1; // More than any possible infected count
int result_node = -1;
// Iterate through each node in `initial` to consider removing it.
for (int node_to_remove : initial) {
vector<bool> visited(n, false);
queue<int> q;
// Set up the initial sources for this simulation.
for (int i : initial) {
if (i != node_to_remove) {
q.push(i);
visited[i] = true;
}
}
// The number of infected nodes starts with the number of initial sources.
int current_infected = q.size();
// Perform a multi-source BFS.
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v = 0; v < n; ++v) {
// The removed node cannot be part of the graph.
if (v == node_to_remove) {
continue;
}
// If there's an edge and the neighbor is not yet infected (visited).
if (graph[u][v] == 1 && !visited[v]) {
visited[v] = true;
current_infected++;
q.push(v);
}
}
}
// Check if this removal is better.
if (current_infected < min_infected) {
min_infected = current_infected;
result_node = node_to_remove;
}
// Because `initial` is sorted, the first node that achieves the minimum
// will be the one with the smallest index. So we don't need to handle
// the `current_infected == min_infected` case.
}
return result_node;
}
};
Minimize Malware Spread II in TypeScript
function minMalwareSpread(graph: number[][], initial: number[]): number {
const n = graph.length;
// Sort initial to handle the tie-breaking rule (smallest index first).
initial.sort((a, b) => a - b);
let minInfected = n + 1; // More than any possible infected count
let resultNode = -1;
// Iterate through each node in `initial` to consider removing it.
for (const nodeToRemove of initial) {
const visited: boolean[] = new Array(n).fill(false);
const queue: number[] = [];
// Set up the initial sources for this simulation.
for (const i of initial) {
if (i !== nodeToRemove) {
queue.push(i);
visited[i] = true;
}
}
// The number of infected nodes starts with the number of initial sources.
let currentInfected = queue.length;
// Perform a multi-source BFS. Use an index to simulate queue for performance.
let head = 0;
while (head < queue.length) {
const u = queue[head++];
for (let v = 0; v < n; v++) {
// The removed node cannot be part of the graph.
if (v === nodeToRemove) {
continue;
}
// If there's an edge and the neighbor is not yet infected (visited).
if (graph[u][v] === 1 && !visited[v]) {
visited[v] = true;
currentInfected++;
queue.push(v);
}
}
}
// Check if this removal is better.
if (currentInfected < minInfected) {
minInfected = currentInfected;
resultNode = nodeToRemove;
}
// Because `initial` is sorted, the first node that achieves the minimum
// will be the one with the smallest index. So we don't need to handle
// the `currentInfected == minInfected` case.
}
return resultNode;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.