Graph Coloring
What is this?
"Colouring" here means the plain version: give every node a component id, then answer questions about the components rather than about the nodes. Minimize Malware Spread is the archetype — a network, a set of initially infected nodes, and the question of which single one to disinfect. The graph work is a routine flood fill. The reasoning after it is what the problem is for.
with its component id"] --> B["per component:
size, and how many infected"] B --> C{"infected count
in this component"} C -->|"2 or more"| D["removing one changes nothing
— the rest still infect it"] C -->|"exactly 1"| E["removing it saves
the whole component"] E --> F["pick the largest such component"] F --> G["tie → smallest node index"]
💡 Fun fact: the trap in Minimize Malware Spread is that removing an infected node usually accomplishes nothing. If its component holds another infected node, the malware reaches every node there anyway and the final count is unchanged. Only a component with exactly one infected node can be saved — which means the answer is decided by a filter most people never apply, and a solution that simulates the spread once per candidate is not just slower, it is easy to get wrong on the tie-break.
🔓 The 1 problem in this chapter is free. Sign in with Google or Microsoft to start solving.
The one-line idea: colour the components, then count. A node is only worth removing if it is the sole infection in its component, and among those the best is the one guarding the most nodes.
1. Colour, then count
colour = [-1] * n
for start in range(n):
if colour[start] == -1:
stack = [start]
while stack:
u = stack.pop()
if colour[u] != -1: continue
colour[u] = start # the first node found is the id
stack += [v for v in range(n) if graph[u][v] and colour[v] == -1]
size = Counter(colour) # nodes per component
infected = Counter(colour[u] for u in initial) # infected per component
Two counters and the rest is arithmetic. The adjacency matrix makes the traversal O(n²), which is fine at n ≤ 300 and worth naming out loud — with an adjacency list it would be O(n + e).
2. The decision
best, best_saved = min(initial), 0
for u in sorted(initial): # ascending → ties resolve themselves
if infected[colour[u]] == 1 and size[colour[u]] > best_saved:
best, best_saved = u, size[colour[u]]
return best
Two details carry the whole answer. The == 1 filter is the insight: a component with two or more infected nodes is doomed regardless. Ascending iteration with a strict > implements "smallest index on a tie" without a special case — and the initial min(initial) covers the case where no component qualifies, where every removal is equally useless and the smallest index wins by default.
3. A 30-second worked example
graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1, 2]
colouring: all three nodes are mutually connected → one component {0,1,2}
size: {c: 3}
infected: {c: 2} ← two infected nodes in the same component
candidate 1: infected[c] == 2, not 1 → skip
candidate 2: infected[c] == 2, not 1 → skip
nothing qualifies → fall back to min(initial) = 1
Removing node 1 leaves node 2 to infect everything; removing node 2 leaves node 1 to do the same. Both end with all three infected, so the answer is decided purely by the tie-break — which is why the fallback is not an edge case to bolt on afterwards but part of the specification.
4. Where you'll actually meet this
- Epidemic and outbreak modelling. Which single quarantine reduces the eventual case count is this question, unchanged.
- Network security. Isolating a compromised host only helps if it is the only compromise in its segment.
- Rumour and misinformation containment. Removing one source matters only when it is the sole source in its cluster.
- Failure-domain analysis. Component size is blast radius, and the counting argument is the same.
- Vaccination strategy. Prioritising by component size is a coarse but real version of targeted immunisation.
5. Problems in this chapter
▶ Minimize Malware Spread
Remove one initially infected node to minimise the final infected count. Colour the components, keep only those with exactly one infection, and pick the largest.
Pattern: component colouring + counting argument. Target: O(n²) on an adjacency matrix, O(n) space.
6. Common pitfalls 🚫
- Removing any infected node and hoping. Only a component with exactly one infection can be saved.
- Simulating the spread once per candidate. Correct but
O(n³), and it still needs the tie-break handled explicitly. - Forgetting the fallback. When no component qualifies the answer is the smallest index in
initial, not-1and not nothing. - Getting the tie-break backwards. Iterate ascending and use a strict
>; the first best index then wins for free. - Confusing size with saved count. What you save is the whole component, not the number of infections in it.
- Assuming the removed node stays clean. It is only removed from the initial set; it can still be infected by neighbours.
- Reading the diagonal as edges.
graph[i][i]is1by definition and is not a real connection.
7. Key takeaways
- Colour the components first, then treat the question as counting.
- Exactly one infection per component is the filter the whole problem turns on.
- The saving is the component's size, not the number of infections in it.
- Ascending iteration plus a strict comparison implements the tie-break with no extra code.
- Handle "nothing qualifies" as part of the spec — it is a common input, not an afterthought.
- Name the representation's cost.
O(n²)here comes from the matrix, not from the algorithm. - Why interviewers like it: the traversal is trivial, so all the signal is in whether you reason about what a removal actually changes.
Order: Minimize Malware Spread.
Minimize Malware Spread
Core idea: Colour every node with its component id, then count two things per component: its size, and how many initially infected nodes it contains. Removing an infected node only helps when it is the sole infection in its component — otherwise the malware spreads through anyway and the final count is unchanged. So filter to components with exactly one infection and pick the one with the largest size. Iterate the candidates in ascending order with a strict
>and the "smallest index on a tie" rule falls out; initialise the answer tomin(initial)so the common case where nothing qualifies is handled by the same code. O(n²) on the adjacency matrix.
Problem Description
title: Minimize Malware Spread
Minimize Malware Spread
Thursday, July 25, 2019
9:14 PM
In a network of nodes, each node i is directly connected to another node j if and only ifgraph[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 willremove one node from the initial list. Return the node that if removed, would minimizeM(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 initiallist of infected nodes, it may still be infected later as a result of the malware spread.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson