Minimize Malware Spread

Hard Graphs Connected Components

Minimize Malware Spread is a hard graphs problem solved with the connected components pattern. The best approach, connected groups with union-find, runs in O(n^2) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from simulate every removal up.

Problem

A network has n nodes, given as an n x n matrix graph where graph[i][j] == 1 means nodes i and j are directly linked. Some nodes, listed in initial, start out infected by malware.

The malware spreads along links: whenever two linked nodes have one of them infected, the other becomes infected too, and this repeats until nothing changes. Let M be the number of infected nodes once the spreading stops.

You must remove exactly one node from initial. The removed node is no longer infected at the start, but it stays in the network and can still catch the malware from a neighbour. Return the node whose removal makes M as small as possible. If several nodes give the same smallest M, return the one with the smallest index.

Examples

Example 1

Input
graph = [[1,1,0,0,0],[1,1,1,0,0],[0,1,1,0,0],[0,0,0,1,1],[0,0,0,1,1]], initial = [1, 3]
Output
1
Why
Nodes 0, 1, 2 form one group and nodes 3, 4 another, each with one infected node. Removing 1 saves its whole group of three, so only 3 and 4 end up infected. Removing 3 would save only two nodes.

Example 2

Input
graph = [[1,1,0,0,0],[1,1,1,0,0],[0,1,1,1,0],[0,0,1,1,0],[0,0,0,0,1]], initial = [2, 0]
Output
0
Why
Nodes 0 to 3 are connected and two of them start infected. Removing either one still leaves the other to infect all four, so both choices give 4 infected nodes. On a tie the smaller index wins: 0.

Example 3

Input
graph = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], initial = [3, 1]
Output
1
Why
No node is linked to any other, so removing either infected node saves exactly one node. The tie goes to the smaller index, 1.

Constraints

  • n == graph.length == graph[i].length, 2 <= n <= 300
  • graph[i][j] is 0 or 1, graph[i][j] == graph[j][i] and graph[i][i] == 1
  • 1 <= initial.length <= n, 0 <= initial[i] < n
  • All values in initial are different.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Simulate every removalO(k * n^2)O(n)
Connected groups with union-findO(n^2)O(n)

1Simulate every removal

TimeO(k * n^2)Each of the k candidates runs a search that may look at every cell of the n by n matrix.
SpaceO(n)The infected marks and the queue hold at most n nodes.

Try each node of initial as the one to remove. Spread the malware from all the other initial nodes with a breadth-first search over the matrix, and count how many nodes end up infected. Keep the candidate with the smallest count, breaking ties by the smaller index.

  1. For each candidate c in initial: start a queue with every initial node except c, all marked infected.
  2. Pop a node u; for every v with graph[u][v] == 1 that is not infected yet, mark it and push it.
  3. When the queue is empty, count the infected nodes.
  4. If the count is smaller than the best so far, or equal with a smaller c, remember c.
class Solution {
    public int minMalwareSpread(int[][] graph, int[] initial) {
        int n = graph.length;
        int best = -1, bestCount = Integer.MAX_VALUE;
        for (int removed : initial) {
            boolean[] infected = new boolean[n];
            ArrayDeque<Integer> queue = new ArrayDeque<>();
            for (int s : initial) {
                if (s != removed) {
                    infected[s] = true;
                    queue.add(s);
                }
            }
            int count = queue.size();
            while (!queue.isEmpty()) {
                int u = queue.poll();
                for (int v = 0; v < n; v++) {
                    if (graph[u][v] == 1 && !infected[v]) {
                        infected[v] = true;
                        count++;
                        queue.add(v);
                    }
                }
            }
            if (count < bestCount || (count == bestCount && removed < best)) {
                bestCount = count;
                best = removed;
            }
        }
        return best;
    }
}

2Connected groups with union-find

TimeO(n^2)Reading the matrix takes n^2 steps; each union and find is almost constant time with union by size and path compression.
SpaceO(n)The parent and size arrays and the per-group infected counts, each of length n.

Malware always ends up filling every connected group that holds at least one infected node. Removing a node therefore helps only when it is the single infected node of its group, and then it saves the whole group. So join the nodes into groups with union-find, record each group's size, count how many initial nodes fall in each group, and among the nodes that are alone in their group pick the one whose group is largest (smaller index on a tie). If no node is alone, nothing can be saved, so return the smallest index in initial.

  1. Union-find over n nodes: for every pair i < j with graph[i][j] == 1, union i and j (by size, with path compression).
  2. For each node s of initial, add one to infectedIn[find(s)].
  3. Start with answer = the smallest value in initial and saved = 0.
  4. For each s in initial whose group has infectedIn == 1: let size be the group's size. If size > saved, or size == saved and s < answer, set answer = s and saved = size.
  5. Return answer.
class Solution {
    private int[] parent, size;

    public int minMalwareSpread(int[][] graph, int[] initial) {
        int n = graph.length;
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if (graph[i][j] == 1) union(i, j);
        int[] infectedIn = new int[n];
        for (int s : initial) infectedIn[find(s)]++;
        int answer = Integer.MAX_VALUE, saved = 0;
        for (int s : initial) answer = Math.min(answer, s);
        for (int s : initial) {
            int root = find(s);
            if (infectedIn[root] != 1) continue;
            if (size[root] > saved || (size[root] == saved && s < answer)) {
                saved = size[root];
                answer = s;
            }
        }
        return answer;
    }

    private int find(int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }

    private void union(int a, int b) {
        int ra = find(a), rb = find(b);
        if (ra == rb) return;
        if (size[ra] < size[rb]) {
            int t = ra;
            ra = rb;
            rb = t;
        }
        parent[rb] = ra;
        size[ra] += size[rb];
    }
}

Edge cases to test

  • One infected node: removing it saves its whole group
  • Every group with an infected node has two or more of them: nothing can be saved, return the smallest index in initial
  • Two candidates save groups of the same size: the smaller index wins
  • initial is not sorted, so the smallest index must be found, not assumed to come first
  • The whole graph is one group
  • Every node starts infected

Hints

Hint 1

The removed node stays in the network and can still be infected by a neighbour. So when does removing it actually help?

Hint 2

Malware fills a whole connected group as soon as one node in it is infected. Think in groups, not in single nodes.

Hint 3

Removing an infected node saves its group only if it is the only infected node in that group, and then it saves the group's full size. Find each node's group and the group sizes, count infected nodes per group, and pick the best.

FAQ

What is the best time complexity for Minimize Malware Spread?

Connected groups with union-find runs in O(n^2) time and O(n) extra space. Reading the matrix takes n^2 steps; each union and find is almost constant time with union by size and path compression.

Which pattern does Minimize Malware Spread use?

It is a graphs problem that uses the connected components pattern. Other problems with the same pattern: Number of Provinces, Number of Islands, Evaluate Division.

Is there a brute force solution for Minimize Malware Spread?

Yes. Simulate every removal takes O(k * n^2) time and O(n) space. Try each node of initial as the one to remove.

Which edge cases should I test for Minimize Malware Spread?

One infected node: removing it saves its whole group; Every group with an infected node has two or more of them: nothing can be saved, return the smallest index in initial; Two candidates save groups of the same size: the smaller index wins; initial is not sorted, so the smallest index must be found, not assumed to come first; The whole graph is one group; Every node starts infected.