> ## 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 II Python Solution

> Tested Python solution for LeetCode 928 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 928, [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-ii/description/).

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

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 928   # by problem number
lcpy gen -s minimize_malware_spread_ii   # 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`, **completely removing it and any connections from this node to any other node**.

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

### Examples

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

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

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

**Explanation:** Removing node 0 still lets the infection reach nodes 1 and 2, `M(2) = 2`. Removing node 1 leaves only node 0 infected, `M(0) = 1`, so return 1.

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

**Explanation:** Removing node 0 lets the infection spread through the chain to nodes 1, 2 and 3, `M(3) = 3`. Removing node 1 leaves only node 0 infected, `M(0) = 1`, so return 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

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2 * alpha(n))
    # Space: O(n)
    def min_malware_spread(self, graph: list[list[int]], initial: list[int]) -> int:
        n = len(graph)
        initial_set = set(initial)
        clean = [node for node in range(n) if node not in initial_set]
        parent: dict[int, int] = {node: node for node in clean}

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

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

        size: dict[int, int] = {}
        for node in clean:
            root = find(node)
            size[root] = size.get(root, 0) + 1

        infecting: dict[int, set[int]] = {}
        for node in clean:
            for source in initial:
                if graph[node][source] == 1:
                    infecting.setdefault(find(node), set()).add(source)

        saved = dict.fromkeys(initial, 0)
        for root, sources in infecting.items():
            if len(sources) == 1:
                saved[next(iter(sources))] += size[root]

        best = initial[0]
        for node in initial:
            if saved[node] > saved[best] or (saved[node] == saved[best] and node < best):
                best = node
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(n^2 \* alpha(n)) | O(n) |

## Tags


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