Maximum Number of K-Divisible Components — LeetCode 2872 Python Solution

HardTreeDepth-First Search
Problem
#2872
Reading time
4 min

The problem

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.

Example

Input
n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6
Output
2
Explanation
We remove the edge connecting node 1 with 2. The resulting split is valid because:

Python solution

Python
class Solution:
    def maxKDivisibleComponents(
        self, n: int, edges: List[List[int]], values: List[int], k: int
    ) -> int:
        def dfs(i: int, fa: int) -> int:
            s = values[i]
            for j in g[i]:
                if j != fa:
                    s += dfs(j, i)
            nonlocal ans
            ans += s % k == 0
            return s

        g = [[] for _ in range(n)]
        for a, b in edges:
            g[a].append(b)
            g[b].append(a)
        ans = 0
        dfs(0, -1)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2872. Maximum Number of K-Divisible Components is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2872. Maximum Number of K-Divisible Components?
LeetCode 2872. Maximum Number of K-Divisible Components is rated Hard on LeetCode.
What is the time complexity of LeetCode 2872. Maximum Number of K-Divisible Components?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2872. Maximum Number of K-Divisible Components?
The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
What topics does LeetCode 2872. Maximum Number of K-Divisible Components cover?
LeetCode 2872. Maximum Number of K-Divisible Components is tagged Tree and Depth-First Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview