Solving Leetcode 2872: Find the Maximum K-Divisible Components

Solving Leetcode 2872: Find the Maximum K-Divisible Components

Leetcode Question Link: https://leetcode.com/problems/maximum-number-of-k-divisible-components/description/

Intuition

Initially, I thought of approaching it with array and tree traversal but didn't think of any other method. I got struck on how to proceed further and looked into the topics, I saw DFS. I checked both BFS and DFS and was getting the wrong components with BFS with my approach. So, I decided to proceed with DFS.

Approach

The approach is to traverse the tree from the bottom up and check if the node is divisible by K. If not then we know, it has to be added with its parent node and check again if the sum of them is divisible by k or not. Likewise, we will check till the root.

  • The sum of the values is bound to be divisible by k, so it has to be some subtree where we will get our sum divisible by k. So we don't have to worry about False cases.

  • We can take root as any node because it’s a tree and doesn't have any cycle so it doesn't matter. I have taken 0 as root.

In the dfs() function,

  • visited set() is used so that we don't visit the same node multiple times.

  • We will store the sum of the current subtree in total.

  • isValid parameter is used to verify whether the subtree is k-divisible or not. If not we will add it to our total (i.e. the current node/parent node value).

  • If the current total is divisible by k , then we got our component. So we will count it in our ans variable and return (True,0) as we got our k-divisible. Otherwise, we will return the total (False,total) to its parent node for further checking.

Complexity

  • Time complexity: O(V+E)

  • Space complexity: O(V)

Code

Python3

class Solution:
    def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
        adjList = collections.defaultdict(list)
        for edge in edges:
            adjList[edge[0]].append(edge[1])
            adjList[edge[1]].append(edge[0])
        self.ans = 0
        visited = set()
        visited.add(0)
        def dfs(node):
            total = values[node]
            for nei in adjList[node]:
                if nei not in visited:
                    visited.add(nei)
                    isValid, temp = dfs(nei)
                    if not isValid:
                        total += temp
            if total % k == 0:
                self.ans+=1
                return (True,0) 
            else:
                return (False,total)

        dfs(0)
        return self.ans

Feel Free to ask any queries.

Thank You :)