You are given a network of n nodes represented as an n × n adjacency matrix graph, where the i-th node is directly connected to the j-th node if graph[i][j] == 1.
Some nodes in 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. 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: If a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.
💡 Note:Nodes 0 and 1 are connected, so removing either still results in both getting infected. Node 2 is isolated. Since both removals give same result, return smaller index 0.
The key insight is to identify which initial node uniquely infects the largest connected component. Use Union-Find to efficiently group nodes into components, then find the initial node whose removal would save the most nodes. Best approach is Union-Find with component analysis. Time: O(n² × α(n)), Space: O(n)
Common Approaches
✓
Brute Force Simulation
⏱️ Time: O(k × n²)
Space: O(n²)
For each node in initial, create a copy without that node, then use DFS/BFS to simulate malware spread and count total infected nodes. Return the removal that gives minimum infection count.
Union-Find with Component Analysis
⏱️ Time: O(n² × α(n))
Space: O(n)
First use Union-Find to group all nodes into connected components. Then for each initial node, determine if removing it would isolate a component that would otherwise be fully infected. Choose the removal that saves the most nodes.
Brute Force Simulation — Algorithm Steps
For each node in initial list
Remove that node and simulate spread using DFS
Count total infected nodes
Return node giving minimum infection count
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Try Remove Node 0
Remove node 0 from initial, simulate spread from node 1
2
Try Remove Node 1
Remove node 1 from initial, simulate spread from node 0
3
Compare Results
Choose removal that gives minimum infected count
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <limits.h>
int countInfected(int** graph, int n, int* initial, int initialSize, int removedNode) {
bool* infected = (bool*)calloc(n, sizeof(bool));
int* queue = (int*)malloc(n * sizeof(int));
int front = 0, rear = 0;
for (int i = 0; i < initialSize; i++) {
if (initial[i] != removedNode) {
infected[initial[i]] = true;
queue[rear++] = initial[i];
}
}
while (front < rear) {
int node = queue[front++];
for (int neighbor = 0; neighbor < n; neighbor++) {
if (graph[node][neighbor] == 1 && !infected[neighbor]) {
infected[neighbor] = true;
queue[rear++] = neighbor;
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (infected[i]) count++;
}
free(infected);
free(queue);
return count;
}
int solution(int** graph, int n, int* initial, int initialSize) {
int minInfected = INT_MAX;
int bestNode = -1;
for (int i = 0; i < initialSize; i++) {
int node = initial[i];
int infectedCount = countInfected(graph, n, initial, initialSize, node);
if (infectedCount < minInfected || (infectedCount == minInfected && (bestNode == -1 || node < bestNode))) {
minInfected = infectedCount;
bestNode = node;
}
}
return bestNode;
}
void parseMatrix(const char* str, int*** graph, int* n) {
// Count rows by counting '[' that are either at start or preceded by ','
*n = 0;
const char* p = str;
bool inOuterArray = false;
while (*p) {
if (*p == '[' && !inOuterArray) {
inOuterArray = true;
} else if (*p == '[' && inOuterArray) {
(*n)++;
}
p++;
}
// Allocate matrix
*graph = (int**)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
(*graph)[i] = (int*)malloc(*n * sizeof(int));
}
// Parse matrix values
p = str;
int row = 0;
// Skip to first inner array
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && row < *n) {
if (*p == '[') {
p++; // skip '['
int col = 0;
while (*p && *p != ']' && col < *n) {
// Skip whitespace and commas
while (*p && (*p == ' ' || *p == ',' || *p == '\n' || *p == '\t')) p++;
if (*p && *p != ']') {
(*graph)[row][col] = (int)strtol(p, (char**)&p, 10);
col++;
}
}
if (*p == ']') p++; // skip ']'
row++;
} else {
p++;
}
}
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
// Find opening bracket
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
// Skip whitespace and commas
while (*p && (*p == ' ' || *p == ',' || *p == '\n' || *p == '\t')) p++;
if (*p && *p != ']') {
arr[*size] = (int)strtol(p, (char**)&p, 10);
(*size)++;
}
}
}
int main() {
char line1[10000], line2[10000];
fgets(line1, sizeof(line1), stdin);
fgets(line2, sizeof(line2), stdin);
// Remove newlines
line1[strcspn(line1, "\n")] = 0;
line2[strcspn(line2, "\n")] = 0;
int** graph;
int n;
parseMatrix(line1, &graph, &n);
int initial[1000];
int initialSize;
parseArray(line2, initial, &initialSize);
printf("%d\n", solution(graph, n, initial, initialSize));
for (int i = 0; i < n; i++) {
free(graph[i]);
}
free(graph);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(k × n²)
For each of k initial nodes, we do DFS traversal taking O(n²) time
n
2n
⚠ Quadratic Growth
Space Complexity
O(n²)
Need to copy the graph and maintain visited arrays for DFS
n
2n
⚡ Linearithmic Space
28.4K Views
MediumFrequency
~35 minAvg. Time
856 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.