> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimize Malware Spread Python Solution

> Tested Python solution for LeetCode 924 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 924, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Union Find](/catalog/topics/union-find), [Graph](/catalog/topics/graph). [View on LeetCode](https://leetcode.com/problems/minimize-malware-spread/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 924   # by problem number
lcpy gen -s minimize_malware_spread   # by problem name
```

## Problem

You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `i<sup>th</sup>` node is directly connected to the `j<sup>th</sup>` 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.

### Examples

```
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
```

**Explanation:** Removing node 0 leaves nodes 1 and 2 infected, so `M(1) = 2`. Removing node 1 leaves nodes 0 and 2 infected, so `M(0) = 2`. Both give the same `M`, so return the smaller index, 0.

```
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
```

**Explanation:** Removing node 0 leaves only node 2 infected, so `M(2) = 1`.

```
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1
```

**Explanation:** Removing either node still leaves all 3 nodes infected, so the smallest index is returned.

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

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimize_malware_spread/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimize_malware_spread/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter


class Solution:
    # Time: O(n^2 * alpha(n)) for the union pass plus O(len(initial)) for the scan
    # Space: O(n)
    def min_malware_spread(self, graph: list[list[int]], initial: list[int]) -> int:
        n = len(graph)
        parent = list(range(n))

        def find(node: int) -> int:
            while parent[node] != node:
                parent[node] = parent[parent[node]]
                node = parent[node]
            return node

        for i in range(n):
            for j in range(i + 1, n):
                if graph[i][j]:
                    root_i, root_j = find(i), find(j)
                    if root_i != root_j:
                        parent[root_i] = root_j

        size = Counter(find(i) for i in range(n))
        infected_in = Counter(find(x) for x in initial)

        best_node = -1
        best_saved = -1
        for x in sorted(initial):
            root = find(x)
            saved = size[root] if infected_in[root] == 1 else 0
            if saved > best_saved:
                best_saved = saved
                best_node = x
        return best_node
```

## Complexity

| Time | Space |
| - | - |
| O(n^2 \* alpha(n)) for the union pass plus O(len(initial)) for the scan | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.