Taro Logo

Minimize Malware Spread

#2 Most AskedHard
0 views
Topics:
Graphs

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.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.

Solution


Clarifying Questions

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:

  1. Can the initial list of infected nodes contain duplicates, and are all nodes in the initial list guaranteed to be valid nodes within the graph?
  2. What should be returned if removing any single node from the initial infected list results in the exact same total number of final infections?
  3. Is the graph guaranteed to be undirected and represented as an adjacency matrix, or could it be directed or represented as an adjacency list?
  4. Can the initial list of infected nodes be empty, and if so, what should be returned?
  5. If the graph contains multiple disconnected components, how should the malware spread across them affect our node removal strategy?

Brute Force Solution

Approach

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:

  1. Start by taking the list of all currently infected computers.
  2. Choose one of the infected computers and pretend to remove the malware from it so it stays healthy.
  3. Simulate how the malware spreads from all the remaining infected computers to any machines they are connected to.
  4. Count the total number of computers that end up getting infected at the end of this simulation.
  5. Write down this final count of sick computers, and then put the malware back on the machine you just tested.
  6. Repeat this entire process of removing, simulating, and counting for every single machine in the original infected list.
  7. Compare the final counts from all your tests and find the one that resulted in the fewest infected computers overall.
  8. Choose that specific machine as the best one to cure, or pick the one with the smallest label if there is a tie.

Code Implementation

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_node

Big(O) Analysis

Time Complexity
O(n^3) – Let n be the number of computers in the network. For each of the initially infected nodes in the list, we simulate the malware spread across the entire network by visiting up to n computers and checking their connections. Since we repeat this complete graph traversal simulation for every single infected node, the cost multiplies by the size of the infected list. This results in approximately n * n * n operations in the worst case, which simplifies to O(n^3).
Space Complexity
O(n) – The auxiliary space complexity is driven by the data structures needed to track visited nodes and simulate malware spread for N computers, where N is the total number of nodes in the network. Specifically, we maintain a visited array or set of size N to keep track of locations during the traversal and simulation steps. Additionally, the simulation may utilize a queue or temporary lists bounded by the size of the network, requiring O(N) extra memory. Thus, the total auxiliary space grows linearly with the input size N, simplifying to Big O notation as O(n).

Optimal Solution

Approach

To 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:

  1. First, map out all the computers and draw lines between the ones that are directly connected to each other, forming isolated neighborhoods of devices.
  2. Look at all the neighborhoods and identify which ones currently have at least one infected computer.
  3. Count how many computers live inside each of those infected neighborhoods to understand their sizes.
  4. Pay special attention to neighborhoods that contain only a single infected computer, because removing that specific infection can potentially save every other computer in that neighborhood.
  5. If a neighborhood has two or more infected computers, removing just one of them will not save any devices because the other infections will still spread unchecked.
  6. Compare all the single-infection neighborhoods and find the one with the highest total population of computers.
  7. If you find a neighborhood where removing the lone infection saves the biggest group of computers, select that infected computer as your target for removal.
  8. If every infected neighborhood contains multiple infections and nobody can be saved, fall back to choosing the infected computer with the smallest original label to keep the result consistent.
  9. By focusing only on these neighborhood populations and infection counts, you immediately know the best computer to remove without wasting time simulating the spread.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n²) – To analyze the time complexity, let n represent the number of computers in the graph, which is given by the rows or columns of the adjacency matrix. The algorithm first explores all connections using a breadth-first search or depth-first search to map the neighborhoods, visiting every possible pair of computers in the matrix, which takes n squared operations. Next, it iterates through the list of initially infected nodes to count neighborhood sizes and evaluate removal candidates, taking additional time proportional to the number of nodes. Since the matrix traversal dominates the overall process, the total operations approximate n times n, which simplifies to Big O of n squared.
Space Complexity
O(n) – To map out the computers and track neighborhoods, the algorithm uses a visited array of size N and a color or component tracking array of size N. Additionally, frequency maps and component size arrays are maintained, each scaling with the number of computers. In the worst-case scenario where all computers form a single line, recursive DFS calls or queue structures will also consume stack or memory proportional to N. Therefore, the total auxiliary space complexity simplifies to Big O of N, where N is the total number of computers.

Edge Cases

Initial malware list contains duplicate node indices
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Maintaining a strict visited set during graph traversal prevents infinite loops and redundant state recalculations.
0/3 completed