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.
Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0
Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0
Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] 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.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine a network of computers where some machines are already infected with malware and it spreads to connected machines. The brute force approach involves testing each infected machine one by one to see what happens if we could magically cure it, and then watching how the malware spreads across the entire network.
Here's how the algorithm would work step-by-step:
def minMalwareSpread(graph, initial): # Sort initial infections to naturally break ties by choosing the smallest node label first initial.sort() minimum_infected_count = float('inf') best_candidate_node = initial[0] for node_to_remove in initial: # Simulate malware spread for each scenario by isolating one initial node at a time active_infected_set = set(initial) active_infected_set.remove(node_to_remove) visited_nodes = set(active_infected_set) traversal_queue = list(active_infected_set) while traversal_queue: current_node = traversal_queue.pop(0) for neighbor_node, is_connected in enumerate(graph[current_node]): if is_connected == 1 and neighbor_node not in visited_nodes: visited_nodes.add(neighbor_node) traversal_queue.append(neighbor_node) total_infected_count = len(visited_nodes) if total_infected_count < minimum_infected_count: # Track the absolute minimum spread and the specific node configuration that caused it minimum_infected_count = total_infected_count best_candidate_node = node_to_remove return best_candidate_nodeTo figure out which infected computer to remove to save the most machines, we can group the computers into connected neighborhoods. By analyzing each neighborhood, we can smartly determine which removal will prevent the most infections without having to test every single possibility.
Here's how the algorithm would work step-by-step:
class Solution:
def minMalwareSpread(self, graph: list[list[int]], initial_nodes: list[int]) -> int:
number_of_nodes = len(graph)
node_colors = {}
color_group = 0
# Group nodes into connected components to isolate neighborhoods and analyze sizes.
for current_node in range(number_of_nodes):
if current_node not in node_colors:
node_colors[current_node] = color_group
stack_of_nodes = [current_node]
while stack_of_nodes:
popped_node = stack_of_nodes.pop()
for neighbor_node in range(number_of_nodes):
if graph[popped_node][neighbor_node] == 1 and neighbor_node not in node_colors:
node_colors[neighbor_node] = color_group
stack_of_nodes.append(neighbor_node)
color_group += 1
component_sizes = [0] * color_group
for current_node in range(number_of_nodes):
component_sizes[node_colors[current_node]] += 1
infection_counts = [0] * color_group
for infected_node in initial_nodes:
infection_counts[node_colors[infected_node]] += 1
best_node_to_remove = -1
max_saved_population = -1
initial_nodes.sort()
# Identify neighborhoods with a single infection to maximize saved computers upon removal.
for infected_node in initial_nodes:
component_id = node_colors[infected_node]
if infection_counts[component_id] == 1:
saved_population = component_sizes[component_id]
if saved_population > max_saved_population:
max_saved_population = saved_population
best_node_to_remove = infected_node
# Fall back to the infected node with the smallest label if no single-infection component exists.
if best_node_to_remove == -1:
best_node_to_remove = initial_nodes[0]
return best_node_to_remove| Case | How to Handle |
|---|---|
| Initial malware list contains duplicate node indices | Convert the initial list to a set or filter unique values to prevent redundant processing and incorrect counts. |
| Graph contains disconnected components or isolated nodes | Graph traversal algorithms like BFS or DFS must iterate through all nodes to ensure every connected component is fully explored. |
| All nodes in the graph are initially infected | The algorithm must correctly handle this boundary state by recognizing that removing any single node still leaves all other nodes infected. |
| No infected nodes are connected to each other | Each infected node resides in its own independent component, meaning removing any single node saves only that exact node. |
| Multiple initial infected nodes belong to the exact same connected component | The solution must detect this overlap because removing one infected node from a multi-infected component yields zero reduction in total malware spread. |
| A tie occurs where removing multiple different nodes yields the exact same minimum total infected count | The selection logic must explicitly compare node indices and favor the one with the smallest numerical value. |
| Maximum-sized graph approaching vertex limits causing time complexity bottlenecks | Using an optimized disjoint set union structure or linear-time component sizing ensures the solution scales efficiently within time limits. |
| Graph contains cycles and bidirectional edges | Maintaining a strict visited set during graph traversal prevents infinite loops and redundant state recalculations. |