You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth 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.
💡 Note:Nodes 0 and 1 are connected and initially infected. Node 2 is isolated. If we remove node 0, only node 1 remains infected. If we remove node 1, only node 0 remains infected. Both removals result in 1 infected node, so return the smaller index 0.
💡 Note:Initial nodes 0,1 are connected. If we remove node 0, the malware spreads from node 1 to nodes 2,3 (total 3 infected). If we remove node 1, only node 0 remains infected (total 1 infected). Removing node 1 minimizes infections.
The optimal approach uses Union-Find to efficiently identify connected components of clean nodes, then determines which initially infected node, when removed, saves the most nodes from infection. The key insight is that removing a node only helps if it's the sole connection to a clean component. Time: O(n²α(n)), Space: O(n).
Common Approaches
✓
Brute Force Simulation
⏱️ Time: O(n³)
Space: O(n²)
For each initially infected node, create a modified graph without that node, then simulate the malware spread using DFS/BFS to count total infected nodes. Return the node whose removal results in minimum infections.
Union-Find with Component Analysis
⏱️ Time: O(n²α(n))
Space: O(n)
First, use Union-Find to identify all connected components in the clean graph (without any initially infected nodes). Then determine which components would be infected by each initially infected node and calculate the optimal removal.
Brute Force Simulation — Algorithm Steps
For each node in initial array, create a copy of the graph
Remove the current node and all its connections from the graph copy
Simulate malware spread from remaining initial nodes using DFS
Count total infected nodes and track the minimum
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Original State
Graph with initially infected nodes [0,1]
2
Remove Node 0
Disconnect node 0 and see spread from node 1
3
Remove Node 1
Disconnect node 1 and see spread from node 0
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
void dfs(int node, int* visited, int** graphCopy, int n) {
if (visited[node]) {
return;
}
visited[node] = 1;
for (int neighbor = 0; neighbor < n; neighbor++) {
if (graphCopy[node][neighbor] == 1 && !visited[neighbor]) {
dfs(neighbor, visited, graphCopy, n);
}
}
}
void parseGraph(const char* str, int*** graph, int* n) {
// Count rows by counting '],['
*n = 1;
const char* p = str;
while ((p = strstr(p, "],[")) != NULL) {
(*n)++;
p += 3;
}
// Allocate graph
*graph = (int**)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
(*graph)[i] = (int*)malloc(*n * sizeof(int));
}
// Parse each row
p = str;
while (*p && *p != '[') p++; // Find first '['
for (int i = 0; i < *n; i++) {
while (*p && *p != '[') p++; // Find row start
if (*p == '[') p++;
for (int j = 0; j < *n; j++) {
while (*p == ' ' || *p == ',') p++;
(*graph)[i][j] = (int)strtol(p, (char**)&p, 10);
}
while (*p && *p != ']') p++; // Find row end
if (*p == ']') p++;
}
}
void parseInitial(const char* str, int** initial, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
// Count elements
const char* temp = p;
while (*temp && *temp != ']') {
while (*temp == ' ' || *temp == ',') temp++;
if (*temp == ']' || *temp == '\0') break;
(*size)++;
while (*temp && *temp != ',' && *temp != ']') temp++;
}
// Allocate and parse
*initial = (int*)malloc(*size * sizeof(int));
int idx = 0;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
(*initial)[idx++] = (int)strtol(p, (char**)&p, 10);
}
}
int solution(int** graph, int n, int* initial, int initialSize) {
int minInfected = INT_MAX;
int result = initial[0];
for (int i = 0; i < initialSize; i++) {
int removeNode = initial[i];
// Create graph copy without removeNode
int** graphCopy = (int**)malloc(n * sizeof(int*));
for (int j = 0; j < n; j++) {
graphCopy[j] = (int*)malloc(n * sizeof(int));
for (int k = 0; k < n; k++) {
graphCopy[j][k] = graph[j][k];
}
}
for (int j = 0; j < n; j++) {
graphCopy[removeNode][j] = 0;
graphCopy[j][removeNode] = 0;
}
int* visited = (int*)calloc(n, sizeof(int));
visited[removeNode] = 1; // Mark removed node as visited
// Start infection from remaining initial nodes
for (int j = 0; j < initialSize; j++) {
int startNode = initial[j];
if (startNode != removeNode && !visited[startNode]) {
dfs(startNode, visited, graphCopy, n);
}
}
// Count infected nodes (excluding removed node)
int infectedCount = 0;
for (int j = 0; j < n; j++) {
if (visited[j]) infectedCount++;
}
infectedCount = infectedCount - 1; // -1 for removed node
if (infectedCount < minInfected || (infectedCount == minInfected && removeNode < result)) {
minInfected = infectedCount;
result = removeNode;
}
// Cleanup
for (int j = 0; j < n; j++) {
free(graphCopy[j]);
}
free(graphCopy);
free(visited);
}
return result;
}
int main() {
char graphLine[1000], initialLine[1000];
fgets(graphLine, sizeof(graphLine), stdin);
fgets(initialLine, sizeof(initialLine), stdin);
// Remove newlines
graphLine[strcspn(graphLine, "\n")] = 0;
initialLine[strcspn(initialLine, "\n")] = 0;
int** graph;
int n;
parseGraph(graphLine, &graph, &n);
int* initial;
int initialSize;
parseInitial(initialLine, &initial, &initialSize);
int result = solution(graph, n, initial, initialSize);
printf("%d\n", result);
// Cleanup
for (int i = 0; i < n; i++) {
free(graph[i]);
}
free(graph);
free(initial);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n³)
For each of n initial nodes, we perform DFS on n nodes, each taking O(n) time
n
2n
⚠ Quadratic Growth
Space Complexity
O(n²)
Need to store graph copy and visited array for DFS traversal
n
2n
⚡ Linearithmic Space
28.5K Views
MediumFrequency
~35 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.