There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
You are also given a 0-indexed integer array values of length n, where values[i] is the value associated with the ith node, and an integer k.
A valid split of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by k, where the value of a connected component is the sum of the values of its nodes.
Return the maximum number of components in any valid split.
💡 Note:We can split the tree by removing the edge between nodes 1 and 2. This creates two components: {0,2} with sum 1+1=2 (not divisible by 6), and {1,3,4} with sum 8+4+4=16 (not divisible by 6). But we can remove edges (1,3) and (1,4) to get components {0,2,1} with sum 10 (not divisible) and {3},{4} with sums 4,4. The optimal split gives us 2 components: {1,4,3} sum=16 and {0,2} sum=2, but since we need divisible sums, we get components {1,3,4} sum=16 and {0,2} sum=2. Actually, the correct split removes edge (0,2) to get {0} sum=1, {2,1,3,4} sum=17. The optimal solution finds 2 valid components.
Example 2 — Single Node
$Input:n = 1, edges = [], values = [10], k = 5
›Output:1
💡 Note:Single node with value 10 is divisible by 5, so we get 1 component.
Maximum Number of K-Divisible Components — Solution
The key insight is to use DFS to greedily cut subtrees when their sums are divisible by k. This maximizes the number of valid components. Best approach is DFS traversal with bottom-up sum calculation. Time: O(n), Space: O(n)
Common Approaches
✓
Brute Force - Try All Edge Removals
⏱️ Time: O(2^n × n²)
Space: O(n²)
Generate all possible subsets of edges to remove, then for each subset check if all resulting connected components have sums divisible by k. This requires checking 2^(n-1) combinations.
DFS with Subtree Sum Checking
⏱️ Time: O(n)
Space: O(n)
Perform a post-order DFS traversal from any node as root. For each subtree, calculate its sum. If the sum is divisible by k, we can cut the edge connecting this subtree to its parent, creating a new component.
Brute Force - Try All Edge Removals — Algorithm Steps
Generate all possible edge removal combinations
For each combination, find connected components
Check if all component sums are divisible by k
Return maximum valid component count
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Generate Combinations
Create all possible edge removal patterns
2
Check Components
For each pattern, find connected components
3
Validate Sums
Check if all component sums are divisible by k
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
static bool visited[30000];
static int component[30000];
static int stack[30000];
typedef struct {
int* neighbors;
int count;
int capacity;
} AdjList;
void addEdge(AdjList* adj, int u, int v) {
if (adj[u].count == adj[u].capacity) {
adj[u].capacity = adj[u].capacity == 0 ? 2 : adj[u].capacity * 2;
adj[u].neighbors = realloc(adj[u].neighbors, adj[u].capacity * sizeof(int));
}
adj[u].neighbors[adj[u].count++] = v;
if (adj[v].count == adj[v].capacity) {
adj[v].capacity = adj[v].capacity == 0 ? 2 : adj[v].capacity * 2;
adj[v].neighbors = realloc(adj[v].neighbors, adj[v].capacity * sizeof(int));
}
adj[v].neighbors[adj[v].count++] = u;
}
int solution(int n, int edges[][2], int edgeCount, int* values, int k) {
if (n == 1) {
return values[0] % k == 0 ? 1 : 0;
}
int maxComponents = 0;
// Try all possible edge removal combinations
for (int mask = 0; mask < (1 << edgeCount); mask++) {
// Build adjacency list
AdjList* adj = calloc(n, sizeof(AdjList));
for (int i = 0; i < edgeCount; i++) {
if (!(mask & (1 << i))) { // Edge not removed
int u = edges[i][0], v = edges[i][1];
addEdge(adj, u, v);
}
}
// Find connected components using DFS
for (int i = 0; i < n; i++) {
visited[i] = false;
}
int componentCount = 0;
bool valid = true;
for (int node = 0; node < n && valid; node++) {
if (!visited[node]) {
// DFS to find component
int top = 0;
int compSize = 0;
stack[top++] = node;
visited[node] = true;
while (top > 0) {
int curr = stack[--top];
component[compSize++] = curr;
for (int i = 0; i < adj[curr].count; i++) {
int neighbor = adj[curr].neighbors[i];
if (!visited[neighbor]) {
visited[neighbor] = true;
stack[top++] = neighbor;
}
}
}
// Check if component sum is divisible by k
long long componentSum = 0;
for (int i = 0; i < compSize; i++) {
componentSum += values[component[i]];
}
if (componentSum % k != 0) {
valid = false;
} else {
componentCount++;
}
}
}
if (valid && componentCount > maxComponents) {
maxComponents = componentCount;
}
// Clean up
for (int i = 0; i < n; i++) {
if (adj[i].neighbors) {
free(adj[i].neighbors);
}
}
free(adj);
}
return maxComponents;
}
int main() {
int n;
scanf("%d", &n);
char line[100000];
fgets(line, sizeof(line), stdin); // consume newline
fgets(line, sizeof(line), stdin); // read edges line
// Parse edges
int edges[30000][2];
int edgeCount = 0;
if (strcmp(line, "[]\n") != 0) {
char* ptr = line + 1; // skip '['
while (*ptr && *ptr != ']') {
if (*ptr == '[') {
ptr++;
int u = strtol(ptr, &ptr, 10);
ptr++; // skip comma
int v = strtol(ptr, &ptr, 10);
edges[edgeCount][0] = u;
edges[edgeCount][1] = v;
edgeCount++;
while (*ptr && *ptr != ']') ptr++;
if (*ptr == ']') ptr++;
} else {
ptr++;
}
}
}
// Parse values
fgets(line, sizeof(line), stdin);
int values[30000];
char* ptr = line + 1; // skip '['
for (int i = 0; i < n; i++) {
values[i] = strtol(ptr, &ptr, 10);
if (*ptr == ',') ptr++;
}
int k;
scanf("%d", &k);
printf("%d\n", solution(n, edges, edgeCount, values, k));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(2^n × n²)
2^(n-1) combinations times O(n²) to check each combination
n
2n
✓ Linear Growth
Space Complexity
O(n²)
Store adjacency lists and visited arrays for component checking
n
2n
⚡ Linearithmic Space
8.5K Views
MediumFrequency
~25 minAvg. Time
234 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.