The Maximum Number of K-Divisible Components coding problem gives you a tree of n nodes, each with a value. You can remove any edges from the tree to split it into components. A component is "k-divisible" if the sum of its node values is divisible by k. Find the maximum number of k-divisible components you can create by removing edges.
Amazon and Google include this problem because it requires a DFS-based greedy observation on trees: when traversing a rooted tree, a subtree can be "cut off" (the edge to its parent removed) if and only if the subtree's total sum is divisible by k. This is a clean tree DP insight that rewards candidates who think recursively.
DFS with greedy cutting: Root the tree at node 0. Perform a post-order DFS. For each node, compute the subtree sum modulo k. If the subtree sum mod k equals 0, this subtree is k-divisible — cut it off (increment count, return 0 to parent so the parent doesn't double-count). Otherwise, return the subtree sum mod k to the parent to accumulate. The initial count is 1 (the whole tree itself, if the total sum is divisible by k). Time: O(n).
Tree: 0-1, 0-2, 1-3. Values: [1, 2, 3, 4]. k=5.
For the Depth-First Search Tree interview pattern, the "cut subtree if sum is divisible by k" insight generalizes to many tree partition problems. The key: returning 0 to the parent after a cut is what makes the greedy work — it ensures the parent doesn't mix the cut subtree's sum into its own. Practice on similar tree component problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Move Sub-Tree of N-Ary Tree | Hard | Solve | |
| Find the Last Marked Nodes in Tree | Hard | Solve | |
| Diameter of N-Ary Tree | Medium | Solve | |
| Maximize the Number of Target Nodes After Connecting Trees II | Hard | Solve | |
| Binary Tree Coloring Game | Medium | Solve |