Minimize Malware Spread
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Minimize Malware Spread
In a network of nodes, some nodes are initially infected with malware. Malware spreads through connected components. You can remove exactly one node from the initial list to minimize total infected nodes. If multiple nodes lead to the same result, return the node with the smallest index.
Optimization Strategy
Only removing an infected node in a component with exactly one initially infected node will actually reduce the total infection (by the size of that component).
Examples
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Approach 1
Level II: DFS (Component Analysis)
Intuition
Use DFS to find all connected components in the graph. For each component, count how many nodes in
initial are part of it. If only one node is infected, removing it saves all nodes in that component. Track the best node to remove.⏱ O(N^2).💾 O(N).
Approach 2
Level III: Union-Find (Component Size Analysis)
Intuition
Build components using Union-Find and record the size of each. For each component, count how many nodes from
initial are in it. If a component has exactly one initial node, moving that node saves size nodes. Pick the one that saves the most.⏱ O(N^2) to build graph components.💾 O(N).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.