question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
delete-duplicate-folders-in-system | [Golang] Trie + DFS + Simple Hashing | golang-trie-dfs-simple-hashing-by-user04-mt6y | go\ntype TrieNode struct {\n hash string\n children map[string]*TrieNode\n}\n\nfunc deleteDuplicateFolder(paths [][]string) [][]string {\n root := &TrieNode{ | user0440H | NORMAL | 2023-02-12T03:56:55.936925+00:00 | 2023-02-12T03:56:55.936958+00:00 | 45 | false | ```go\ntype TrieNode struct {\n hash string\n children map[string]*TrieNode\n}\n\nfunc deleteDuplicateFolder(paths [][]string) [][]string {\n root := &TrieNode{children: make(map[string]*TrieNode)}\n for _, path := range paths {\n insert(root, path)\n }\n // Now we\'re going to do a DFS to compute hash for each node\n // As part of that we\'re also going to count the occurrences of each hash key\n hashCounts := make(map[string]int)\n dfs(root, hashCounts)\n var res [][]string\n render(root, hashCounts, nil, &res)\n return res\n}\n\nfunc render(root *TrieNode, hashCounts map[string]int, curr []string, res *[][]string) {\n if len(curr) > 0 {\n // Make a copy so when we go down the tree the slice doesn\'t get modified in \n // the final result.\n curr2 := make([]string, len(curr))\n copy(curr2, curr)\n *res = append(*res, curr2)\n }\n for key, child := range root.children {\n if hashCounts[child.hash] > 1 { // duplicate; discard the entire subtree here\n continue\n }\n curr = append(curr, key)\n render(child, hashCounts, curr, res)\n curr = curr[:len(curr)-1]\n }\n}\n\nfunc dfs(root *TrieNode, hashCounts map[string]int) {\n // We\'re going to process the keys in sorted order\n // We compute hash simply using \'(\' and \')\'\n // For example x(y)(z) is the hash of a directory that contains\n // x and x contains y and z as child directories.\n var h string\n for _, key := range sortedKeys(root.children) {\n dfs(root.children[key], hashCounts)\n var currHash string\n if root.children[key].hash != "" {\n currHash = fmt.Sprintf("%s(%s)", key, root.children[key].hash)\n } else {\n currHash = fmt.Sprintf("%s", key)\n }\n h += currHash\n }\n if h != "" {\n hashCounts[h]++\n }\n root.hash = h\n}\n\nfunc sortedKeys(m map[string]*TrieNode) []string {\n keys := make([]string, 0, len(m))\n for k := range m {\n keys = append(keys, k)\n }\n sort.Strings(keys)\n return keys\n}\n\nfunc insert(root *TrieNode, path []string) {\n curr := root\n for i := 0; i < len(path); i++ {\n child := curr.children[path[i]]\n if child == nil {\n child = &TrieNode{children: make(map[string]*TrieNode)}\n curr.children[path[i]] = child\n }\n curr = child\n }\n}\n``` | 0 | 0 | ['Depth-First Search', 'Trie', 'Go'] | 0 |
delete-duplicate-folders-in-system | Fast and readable C++ solution using tries | fast-and-readable-c-solution-using-tries-m8bn | Intuition\nConstruct a trie and compute a serial identifier for the nodes.\n\n# Approach\n1. Construct a trie from the input paths.\n2. Compute an identifier fo | daniel404 | NORMAL | 2023-02-02T00:43:12.888930+00:00 | 2023-02-02T00:43:12.888969+00:00 | 103 | false | # Intuition\nConstruct a trie and compute a serial identifier for the nodes.\n\n# Approach\n1. Construct a trie from the input paths.\n2. Compute an identifier for each node in the trie, and locate duplicates.\n3. Output nodes with unique identifiers.\n\nMost importantly, the identifier we compute in step 2 must have a 1:1 mapping with the subdirectory structure from that node. E.g. two distinct subdirectory structures cannot map to the same id, and two distinct ids cannot map to the same subdirectory structure.\n\n# Code\n```\nclass Trie {\npublic:\n // Recursively insert a path into this Trie.\n void insert(vector<string>::iterator current, vector<string>::iterator end) {\n if (current != end) {\n // Insert the rest of the path into the child node.\n children_[*current].insert(++current, end);\n }\n }\n\n // Get a string which uniquely identifies the structure of this Trie node\n // (and all of its children), but does not include the name of this Trie node\n // itself (because two folders with different names can still be duplicates).\n const string& partial_id() {\n if (!serial_id_.empty()) {\n return serial_id_;\n }\n for (auto& [child_name, child] : children_) {\n serial_id_ += child_name + "(" + child.partial_id() + "),";\n }\n return serial_id_;\n }\n\n map<string, Trie> children_;\n string serial_id_;\n};\n\nclass Solution {\npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n // Build the trie.\n Trie root;\n for (vector<string>& path : paths) {\n root.insert(path.begin(), path.end());\n }\n\n // Find the duplicates.\n unordered_map<string, int> count;\n count_ids(root, count);\n\n // Find the nonduplicates.\n vector<string> current_path;\n vector<vector<string>> nonduplicates;\n gather_nonduplicates(root, count, current_path, nonduplicates);\n return nonduplicates;\n }\n\nprivate:\n // Recursively count the number of occurrences for each partial id\n // in the given Trie.\n void count_ids(Trie& current, unordered_map<string, int>& count) {\n count[current.partial_id()]++;\n for (auto& [child_name, child] : current.children_) {\n count_ids(child, count);\n }\n }\n\n // Traverse the tree and append non-duplicated folders to `non_duplicates`.\n void gather_nonduplicates(Trie& current,\n const unordered_map<string, int>& count,\n vector<string>& current_path,\n vector<vector<string>>& nonduplicates) {\n if (current.partial_id().empty()) {\n // Root nodes are never considered duplicates unless\n // their parents are also duplicates.\n nonduplicates.push_back(current_path);\n return;\n }\n\n if (count.at(current.partial_id()) != 1) {\n // This node (and all children) is a duplicate.\n // No need to continue traversing.\n return;\n }\n\n if (!current_path.empty()) {\n // Avoid edge case causing empy output for root node.\n nonduplicates.push_back(current_path);\n }\n\n // Traverse children.\n for (auto& [child_name, child] : current.children_) {\n current_path.push_back(child_name);\n gather_nonduplicates(child, count, current_path, nonduplicates);\n current_path.pop_back();\n }\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
delete-duplicate-folders-in-system | hash map by converting internal folder structures to strings | hash-map-by-converting-internal-folder-s-5o88 | Approach\n- build nested dictionary structure\n- create sets/maps of structures found\n- filter for unique structures\n\n# Complexity\nN = number of folders\n\n | kesslwovv | NORMAL | 2022-12-09T19:58:39.144373+00:00 | 2022-12-09T19:58:39.144419+00:00 | 130 | false | # Approach\n- build nested dictionary structure\n- create sets/maps of structures found\n- filter for unique structures\n\n# Complexity\nN = number of folders\n\n- Time complexity:\nbuild nested dictionary structure: O(N)\ncreate sets/maps of structures found: O(N * N)\nfilter for unique structures: O(N)\n__Overall: O(N*N)__\n- Space complexity:\nbuild nested dictionary structure: O(N)\ncreate sets/maps of structures found: O(N)\nfilter for unique structures: O(N)\n__Overall: O(N)__\n\n# Code\n```\n# get the inner structure of the folder recursively\ndef get_path(folder):\n out = "/"\n\n # sort required because different folders might have\n # different order of subfolders\n for key in sorted(folder.keys()):\n out += key\n out += get_path(folder[key])\n\n out += ";"\n return out\n\n# traverse a nested dictionary structure\ndef get_nested_item(itemarray, nested):\n item = nested\n for key in itemarray:\n item = item[key]\n return item\n\nclass Solution(object):\n def deleteDuplicateFolder(self, paths):\n """\n :type paths: List[List[str]]\n :rtype: List[List[str]]\n """\n\n # build nested dictionary representing folders\n mapping = {}\n for path in paths:\n cur_folder = mapping\n for folder in path:\n cur_folder.setdefault(folder, {})\n cur_folder = cur_folder[folder]\n\n # the top level node is not in path but still\n # needs to be present in the dict\n internal_structure = {(): \'/;\'}\n # could also be implemented using a dict and counting occurences\n structures_found = set()\n structures_multiple = set()\n\n # create maps of structures found\n for path in paths:\n path_str = get_path(get_nested_item(path, mapping))\n internal_structure[tuple(path)] = path_str\n if path_str != \'/;\':\n if path_str not in structures_found:\n structures_found.add(path_str)\n elif path_str not in structures_multiple:\n structures_multiple.add(path_str)\n \n # only append those paths that are not present\n remaining = []\n for path in paths:\n structure = internal_structure[tuple(path)]\n if structure == \'/;\':\n structure = internal_structure[tuple(path[:-1])]\n if structure in structures_multiple:\n pass\n else:\n remaining.append(path)\n\n return remaining\n\n``` | 0 | 0 | ['Python'] | 0 |
delete-duplicate-folders-in-system | [Java] Simple Trie + DFS Solution | java-simple-trie-dfs-solution-by-samuel3-p4h0 | Code\n\nclass Solution {\n class TrieNode {\n TreeMap<String, TrieNode> children;\n boolean isEndOfDir;\n boolean deleted;\n \n | Samuel3Shin | NORMAL | 2022-11-12T19:30:17.961848+00:00 | 2022-11-12T19:30:17.961896+00:00 | 265 | false | # Code\n```\nclass Solution {\n class TrieNode {\n TreeMap<String, TrieNode> children;\n boolean isEndOfDir;\n boolean deleted;\n \n public TrieNode() {\n children = new TreeMap<>();\n isEndOfDir = false;\n deleted = false;\n }\n }\n\n public void insert(TrieNode root, List<String> path) {\n TrieNode cur = root;\n \n for(int depth=0; depth<path.size(); depth++) {\n String ch = path.get(depth);\n \n if(!cur.children.containsKey(ch)) {\n cur.children.put(ch, new TrieNode());\n }\n \n cur = cur.children.get(ch);\n }\n \n cur.isEndOfDir = true;\n \n }\n\n TrieNode root;\n HashMap<String, ArrayList<TrieNode>> hm;\n List<List<String>> ansLst;\n \n public List<List<String>> deleteDuplicateFolder(List<List<String>> paths) {\n root = new TrieNode();\n hm = new HashMap<>();\n ansLst = new ArrayList<>();\n\n for(int i=0; i<paths.size(); i++) {\n insert(root, paths.get(i));\n }\n\n // Store all the child structures of Nodes in HashMap\n dfs(root);\n\n // If the node has the same child structure with other nodes,\n // make node.deleted = true.\n for(String key : hm.keySet()) {\n if(hm.get(key).size() > 1) {\n for(TrieNode node : hm.get(key)) {\n node.deleted = true;\n }\n }\n }\n\n // Traverse to store survived Nodes in the Trie.\n helper(root, new ArrayList<>());\n\n return ansLst; \n }\n\n public void helper(TrieNode root, ArrayList<String> lst) {\n if(root.deleted) return;\n\n for(String key: root.children.keySet()) {\n lst.add(key);\n helper(root.children.get(key), lst);\n lst.remove(lst.size()-1);\n }\n\n if(lst.size() > 0) {\n ArrayList<String> tmp = new ArrayList<>();\n for(String s : lst) {\n tmp.add(s);\n }\n ansLst.add(tmp);\n }\n }\n\n public String dfs(TrieNode root) {\n StringBuilder sb = new StringBuilder();\n \n for(String key: root.children.keySet()) {\n sb.append(key + "#");\n }\n\n for(String key: root.children.keySet()) {\n sb.append("$" + dfs(root.children.get(key)));\n }\n \n if(!hm.containsKey(sb.toString())) {\n hm.put(sb.toString(), new ArrayList<>());\n }\n\n if(sb.toString().length() > 0) {\n hm.get(sb.toString()).add(root);\n }\n\n return sb.toString();\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
delete-duplicate-folders-in-system | solutions in C++ | solutions-in-c-by-infox_92-5yqp | \nclass Solution {\n struct Node {\n map<string,Node*> child;\n bool duplicate=false;\n };\n \n void build(Node* root,vector<vecto | Infox_92 | NORMAL | 2022-10-31T10:44:10.621080+00:00 | 2022-10-31T10:44:10.621120+00:00 | 46 | false | ```\nclass Solution {\n struct Node {\n map<string,Node*> child;\n bool duplicate=false;\n };\n \n void build(Node* root,vector<vector<string>>& paths) {\n for (auto& dirs : paths) {\n Node* node=root;\n for (auto& dir : dirs) {\n if (node->child.count(dir) == 0) \n node->child[dir] = new Node;\n node = node->child[dir];\n }\n }\n }\n \n string prune(Node* node,unordered_map<string,vector<Node*>>& subdirs) {\n if (node->child.size() == 0) \n return "";\n \n string subdir("(");\n for (auto& [dir,child] : node->child) \n subdir += dir + prune(child,subdirs); \n subdir += ")";\n \n auto& nodes = subdirs[subdir];\n nodes.push_back(node);\n \n if (nodes.size() > 1) {\n nodes.front()->duplicate = true;\n nodes.back()->duplicate = true;\n }\n return subdir;\n }\n\n void gather(Node *node,vector<string>& path,vector<vector<string>>& result) {\n if (node->duplicate == false) {\n if (path.size())\n result.push_back(path);\n for (auto& [dir, child] : node->child) {\n path.push_back(dir);\n gather(child,path,result);\n path.pop_back();\n }\n }\n }\n \npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n Node root;\n build(&root,paths); \n \n unordered_map<string,vector<Node*>> subdirs;\n prune(&root,subdirs);\n \n vector<vector<string>> result;\n vector<string> path; \n gather(&root,path,result);\n \n return result;\n }\n};\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Python3 with tree hash | python3-with-tree-hash-by-jeremyxu555-v388 | \nimport collections\nfrom typing import List\nfrom sortedcontainers import SortedDict\n\n\nclass TreeNode:\n def __init__(self, val):\n self.val = va | jeremyxu555 | NORMAL | 2022-10-31T00:38:25.644846+00:00 | 2022-10-31T00:38:25.644879+00:00 | 158 | false | ```\nimport collections\nfrom typing import List\nfrom sortedcontainers import SortedDict\n\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.children = SortedDict()\n\n\nclass Solution:\n def __init__(self):\n self.key2Id = {}\n self.key2Count = collections.defaultdict(int)\n self.node2Key = {}\n self.res = []\n\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n root = TreeNode(\'/\')\n for path in paths:\n node = root\n for c in path:\n if c not in node.children:\n node.children[c] = TreeNode(c)\n node = node.children[c]\n\n self.get_id(root)\n self.dfs(root, [])\n\n return self.res\n\n def get_id(self, node):\n if not node:\n return 0\n key = \'\'\n for child in node.children.values():\n key += str(self.get_id(child)) + \'#\' + child.val + \'#\'\n\n self.node2Key[node] = key\n self.key2Count[key] += 1\n if self.key2Count[key] == 1:\n self.key2Id[key] = len(self.key2Id) + 1\n\n return self.key2Id[key]\n\n def dfs(self, node, path):\n key = self.node2Key[node]\n if self.key2Count[key] >= 2 and key != \'\':\n return\n if node.val != \'/\':\n path.append(node.val)\n self.res.append(path.copy())\n\n for child in node.children.values():\n self.dfs(child, path.copy())\n\n if node.val != \'/\':\n path.pop()\n\n\nif __name__ == \'__main__\':\n s = Solution()\n # print(s.deleteDuplicateFolder([["a"], ["c"], ["d"], ["a", "b"], ["c", "b"], ["d", "a"]]))\n print(s.deleteDuplicateFolder(\n [["b"], ["f"], ["f", "r"], ["f", "r", "g"], ["f", "r", "g", "c"], ["f", "r", "g", "c", "r"], ["f", "o"],\n ["f", "o", "x"], ["f", "o", "x", "t"], ["f", "o", "x", "d"], ["f", "o", "l"], ["l"], ["l", "q"], ["c"], ["h"],\n ["h", "t"], ["h", "o"], ["h", "o", "d"], ["h", "o", "t"]]\n ))\n``` | 0 | 0 | ['Python3'] | 0 |
delete-duplicate-folders-in-system | C++ | Trie accepted solution | c-trie-accepted-solution-by-nick-thurn-0p53 | One thing that had me stuck was understanding that the whole subtree of a node needs to be compared. This is actually easier than trying to separate the individ | nick-thurn | NORMAL | 2022-10-03T05:07:38.468033+00:00 | 2022-10-03T05:32:21.901648+00:00 | 66 | false | One thing that had me stuck was understanding that the whole subtree of a node needs to be compared. This is actually easier than trying to separate the individual paths. \n\nThere is also no reason to do the pruning in two steps as all the data is available when you add a second/third/forth parent node to the same subdirectory structure.\n\nIn anycase hope this helps someone.\n\nAll the best!!\n\n\n\n```\nclass Solution {\n struct Node {\n map<string,Node*> child;\n bool duplicate=false;\n };\n \n void build(Node* root,vector<vector<string>>& paths) {\n for (auto& dirs : paths) {\n Node* node=root;\n for (auto& dir : dirs) {\n if (node->child.count(dir) == 0) \n node->child[dir] = new Node;\n node = node->child[dir];\n }\n }\n }\n \n string prune(Node* node,unordered_map<string,vector<Node*>>& subdirs) {\n if (node->child.size() == 0) \n return "";\n \n string subdir("(");\n for (auto& [dir,child] : node->child) \n subdir += dir + prune(child,subdirs); \n subdir += ")";\n \n auto& nodes = subdirs[subdir];\n nodes.push_back(node);\n \n if (nodes.size() > 1) {\n nodes.front()->duplicate = true;\n nodes.back()->duplicate = true;\n }\n return subdir;\n }\n\n void gather(Node *node,vector<string>& path,vector<vector<string>>& result) {\n if (node->duplicate == false) {\n if (path.size())\n result.push_back(path);\n for (auto& [dir, child] : node->child) {\n path.push_back(dir);\n gather(child,path,result);\n path.pop_back();\n }\n }\n }\n \npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n Node root;\n build(&root,paths); \n \n unordered_map<string,vector<Node*>> subdirs;\n prune(&root,subdirs);\n \n vector<vector<string>> result;\n vector<string> path; \n gather(&root,path,result);\n \n return result;\n }\n};\n```` | 0 | 0 | ['Depth-First Search', 'Trie', 'C'] | 0 |
delete-duplicate-folders-in-system | Java Solution | Using Trie With PostOrder And InOrder DFS Traversal | java-solution-using-trie-with-postorder-0i18j | Steps :\n\n1. Build a Trie. Here I am using map for the children node because node value is a string, not a single character.\n\n2. PostOrder - For duplication | nitwmanish | NORMAL | 2022-10-01T14:01:35.752117+00:00 | 2022-11-05T02:33:41.606851+00:00 | 187 | false | Steps :\n\n1. Build a Trie. Here I am using map for the children node because node value is a string, not a single character.\n\n2. PostOrder - For duplication detection in tree.\n* The substructure is encoded using \'(\' and \')\' to denote levels e.g. a (b, c,d (...),) \n* Order of node\'s children is important. For example \'a(b,c)\' vs \'a(c,b)\'. Using TreeMap for node.children.\n* Record substructure int a map<String, Node> with key is a serialized structure string.\n* Mark the node.duplicate = true if its substructure has seen earlier.\n\n3. DFS and stop at nodes which node.dup=true.\n```\nclass Solution {\n private static class Node {\n\t\tprivate String val;\n\t\tprivate boolean duplicate;\n\t\tprivate Map<String, Node> children;\n\n\t\tpublic Node(String val) {\n\t\t\tthis.val = val;\n\t\t\tthis.duplicate = false;\n\t\t\tthis.children = new TreeMap<String, Node>();\n\t\t}\n\t}\n\n\tprivate Node root = new Node("/");\n\n\tprivate String postOrder(Node curr, Map<String, Node> map) {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tfor (Node child : curr.children.values()) {\n\t\t\tsb.append(postOrder(child, map));\n\t\t\tsb.append(",");\n\t\t}\n\n\t\tString key = sb.toString();\n\t\tif (sb.length() == 0) {\n\t\t\treturn curr.val + key; // leaf node\n\t\t}\n\t\tif (map.containsKey(key)) {\n\t\t\tNode orig = map.get(key);\n\t\t\torig.duplicate = true;\n\t\t\tcurr.duplicate = true;\n\t\t} else {\n\t\t\tmap.put(key, curr);\n\t\t}\n\n\t\treturn curr.val + "(" + key + ")";\n\t}\n\n\tprivate void inOrder(List<List<String>> ans, Node node, List<String> list) {\n\t\tif (node == null) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Node child : node.children.values()) {\n\t\t\tif (child.duplicate) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlist.add(child.val);\n\t\t\tans.add(new ArrayList<>(list));\n\t\t\tinOrder(ans, child, list);\n\t\t\tlist.remove(list.size() - 1);\n\t\t}\n\t}\n\n\tprivate void insertPath(List<String> path) {\n\t\tNode curr = this.root;\n\t\tfor (String folder : path) {\n\t\t\tif (!curr.children.containsKey(folder)) {\n\t\t\t\tcurr.children.put(folder, new Node(folder));\n\n\t\t\t}\n\t\t\tcurr = curr.children.get(folder);\n\t\t}\n\t}\n\n public List<List<String>> deleteDuplicateFolder(List<List<String>> paths) {\n for (List<String> path : paths) {\n\t\t\tinsertPath(path);\n\t\t}\n\t\tMap<String, Node> map = new HashMap<>();\n\t\tpostOrder(this.root, map);\n\t\tList<List<String>> ans = new ArrayList<>();\n\t\tinOrder(ans, this.root, new ArrayList<String>());\n\t\treturn ans;\n }\n}\n```\nSome Other Problems Using Trie Data Structure \n[1268 : Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/discuss/2638534/java-solution-using-trie-runtime-37-ms-beats-7219)\n[1233 : Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/2638522/java-solution-using-trie-runtime-43-ms-beats-9605)\n[648\t: Replace Words](https://leetcode.com/problems/replace-words/discuss/2638625/java-solution-using-trie-runtime-14-ms-beats-962219)\n[820\t: Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/discuss/2639021/java-solution-using-trie)\n[208\t: Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/discuss/2638657/simple-java-solution)\n[386\t: Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/discuss/2639107/java-solution-using-trie)\n[1023 : Camelcase Matching](https://leetcode.com/problems/camelcase-matching/discuss/2639736/java-solution-using-trie)\n[677\t: Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/discuss/2639994/java-solution-using-trie-and-hashmap)\n[676\t: Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/discuss/2640276/java-solution-using-trie)\n[421\t: Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/2643276/java-trie-approach-add-number-and-check-its-max-xor-on-fly-tc-on-and-sc-on)\n[792\t: Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/discuss/2643489/java-solutions-two-approach-1-using-trie-2-hashmap)\n[720\t: Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/discuss/2643586/java-solution-using-trie-dfs)\n[2261 : K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2643761/java-solution-sliding-window-trie-runtime-41-ms-faster-than-9846)\n[139\t: Word Break](https://leetcode.com/problems/word-break/discuss/2643915/java-solutions-two-approach-1-using-trie-bfs-2-dp)\n[211\t: Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/discuss/2643839/java-solution-using-trie-dfs)\n[1948 : Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/2646138/java-solution-using-trie-with-postorder-and-inorder-dfs-traversal)\n[1032 : Stream of Characters](https://leetcode.com/problems/stream-of-characters/discuss/2646970/java-solution-using-trie)\n[212. Word Search II](https://leetcode.com/problems/word-search-ii/discuss/2779677/Java-Solution-or-Using-Trie) | 0 | 0 | ['Tree', 'Depth-First Search', 'Trie', 'Java'] | 0 |
delete-duplicate-folders-in-system | Python solution | python-solution-by-chienwen-okr9 | My approach: generate a "signature" for each node as:\na(...)c(...)d(...), where the children a, c, d should be sorted.\n... is the signature of grandchildren.\ | chienwen | NORMAL | 2022-09-22T17:55:50.769376+00:00 | 2022-09-22T17:55:50.769421+00:00 | 101 | false | My approach: generate a "signature" for each node as:\n`a(...)c(...)d(...)`, where the children a, c, d should be sorted.\n`...` is the signature of grandchildren.\n\n```python\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n \n # build the trie\n trie = {}\n for path in paths:\n current = trie\n for p in path:\n if p not in current:\n current[p] = {}\n current = current[p]\n \n # calculate signature for all nodes on the trie\n sig_counter = collections.Counter()\n def dfs(node):\n sig = []\n for key in sorted(node.keys()):\n sig.append(key + "(" + dfs(node[key]) + ")")\n node[\'#\'] = "".join(sig)\n if sig:\n sig_counter[node[\'#\']] += 1\n return node[\'#\'] \n dfs(trie)\n \n # traverse the trie and keep only sig_counter < 2\n outputs = []\n def dfsOutput(node, path):\n for key in node:\n if key != \'#\':\n sig = node[key][\'#\']\n if sig_counter[sig] < 2:\n output = path.copy()\n output.append(key)\n outputs.append(output)\n dfsOutput(node[key], output)\n dfsOutput(trie, [])\n \n return outputs\n```\n | 0 | 0 | ['Python'] | 0 |
delete-duplicate-folders-in-system | Python Implementation using concept of Trie | python-implementation-using-concept-of-t-t0go | \nclass TrieNode:\n def __init__(self):\n self.children = defaultdict(TrieNode)\n self.hash, self.isDeleted = \'\', False\n \n def ad | hemantdhamija | NORMAL | 2022-09-14T06:54:27.873459+00:00 | 2022-09-14T06:54:27.873500+00:00 | 144 | false | ```\nclass TrieNode:\n def __init__(self):\n self.children = defaultdict(TrieNode)\n self.hash, self.isDeleted = \'\', False\n \n def add(self, path, idx = 0):\n if idx != len(path):\n self.children[path[idx]].add(path, idx + 1)\n \n def calculateHash(self, hashes, nodeName = \'root\'):\n for childNodeName, childNode in sorted(self.children.items()):\n self.hash += f\'{childNode.calculateHash(hashes, childNodeName)}+\'\n if self.hash:\n hashes[self.hash].append(self)\n return f\'{nodeName}({self.hash})\'\n \n def toList(self, lst, path = []):\n for childNodeName, childNode in self.children.items():\n if not childNode.isDeleted:\n lst.append(path + [childNodeName])\n childNode.toList(lst, path + [childNodeName])\n\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n root, hashToNodes, res = TrieNode(), defaultdict(list), []\n for path in paths:\n root.add(path)\n root.calculateHash(hashToNodes)\n for nodes in hashToNodes.values():\n if len(nodes) > 1:\n for node in nodes:\n node.isDeleted = True\n root.toList(res)\n return res\n``` | 0 | 0 | ['Tree', 'Depth-First Search', 'Trie', 'Recursion', 'Python'] | 0 |
delete-duplicate-folders-in-system | [C++] O(N) Trie + Merkle Tree w/ Custom Hashing (GCC std::hash has collisions) | c-on-trie-merkle-tree-w-custom-hashing-g-vn9m | Basically, this is my thought process:\n- Trie: I need to "compress" all the paths with their parent paths into one tree, so [a], [a,b], [a,b,c] turns into [a,b | CelonyMire | NORMAL | 2022-09-03T18:27:59.580867+00:00 | 2022-09-03T18:30:57.112201+00:00 | 76 | false | Basically, this is my thought process:\n- Trie: I need to "compress" all the paths with their parent paths into one tree, so `[a], [a,b], [a,b,c]` turns into `[a,b,c]`. It is also good for getting the remaining paths after removal of duplicate folders.\n- Merkle Tree: Efficient computation of hashes for each subtree. Note for for getting the hash of each subtree, **we DO NOT include the subtree\'s root folder name!** This is because we only care about the structure underneath the parent folders, the names of the parent folders do not matter.\n\nOther solutions hash the traversals of the subtrees, but that is not ideal for more complicated problems because of the repeated string concatenation, which leads up to O(N^2). \n\n---\n\n```cpp\n#define vec vector\n#define umap unordered_map\n\nusing vs = vec<string>;\nusing vvs = vec<vec<string>>;\n\ntemplate <typename T, typename = void> struct is_tuple_like {\n static constexpr bool value = false;\n};\ntemplate <typename T>\nstruct is_tuple_like<T, void_t<typename tuple_size<T>::type>> {\n static constexpr bool value = true;\n};\ntemplate <typename T, typename = void> struct is_hashable {\n static constexpr bool value = false;\n};\ntemplate <typename T> struct is_hashable<T, void_t<decltype(hash<T>{}(T{}))>> {\n static constexpr bool value = true;\n};\nvec<size_t> VALS;\nstruct custom_hash {\n static size_t getfixed(int i) {\n while ((int)VALS.size() < i + 1)\n if (VALS.empty())\n VALS.push_back(\n (size_t)chrono::steady_clock::now().time_since_epoch().count());\n else\n VALS.push_back(splitmix64(VALS.back()));\n return VALS[i];\n }\n static size_t splitmix64(size_t x) {\n x += (size_t)0x9e3779b97f4a7c15;\n x = (x ^ (x >> (size_t)30)) * (size_t)0xbf58476d1ce4e5b9;\n x = (x ^ (x >> (size_t)27)) * (size_t)0x94d049bb133111eb;\n return x ^ (x >> (size_t)31);\n }\n template <typename T>\n enable_if_t<is_hashable<T>::value, size_t> operator()(const T &t) const {\n return splitmix64(hash<T>{}(t) + getfixed(0));\n }\n template <typename T>\n enable_if_t<is_tuple_like<T>::value, size_t> operator()(const T &t) const {\n int ic = 0;\n size_t rh = 0;\n apply(\n [&](auto &&...args) {\n ((rh ^=\n splitmix64(hash<decay_t<decltype(args)>>{}(args) + getfixed(ic++))),\n ...);\n },\n t);\n return rh;\n }\n};\n\nstruct trie {\n struct node {\n umap<string, node *> adj;\n size_t hash = 0;\n };\n node *root = new node();\n umap<size_t, int> subtrees;\n void insert(vs &s) {\n auto cur = root;\n for (int i = 0; i < s.size(); i++) {\n auto &next = cur->adj[s[i]];\n if (!next)\n next = new node();\n cur = next;\n }\n }\n void paths(node *cur, vs &path, vvs &ans) {\n for (auto &[a, next] : cur->adj) {\n if (next) {\n path.push_back(a);\n ans.push_back(path);\n paths(next, path, ans);\n path.pop_back();\n }\n }\n }\n size_t compute_merkle(node *cur) {\n size_t combined_hash = 0;\n for (auto &[child, next] : cur->adj) {\n combined_hash +=\n custom_hash{}(custom_hash{}(child) + compute_merkle(next));\n\t // ^ We hash together the name of the children\'s folder with the hash of its\n\t // substructures to make sure they came from the same children\n }\n cur->hash = custom_hash{}(combined_hash);\n subtrees[cur->hash]++;\n return cur->hash;\n }\n void delete_duplicates(node *cur) {\n for (auto &[_, next] : cur->adj) {\n delete_duplicates(next);\n if (!next->adj.empty() && subtrees[next->hash] > 1) {\n next = nullptr;\n }\n }\n }\n};\n\nclass Solution {\npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>> &paths) {\n trie t;\n for (auto &path : paths) {\n t.insert(path);\n }\n t.compute_merkle(t.root);\n t.delete_duplicates(t.root);\n\n vvs ans;\n vs path;\n t.paths(t.root, path, ans);\n return ans;\n }\n};\n``` | 0 | 0 | ['Depth-First Search', 'Trie', 'C', 'Hash Function'] | 0 |
delete-duplicate-folders-in-system | ✔️ [Javascript] solution || Very simple | javascript-solution-very-simple-by-kagoo-11bi | This is not my answer. I found it in this Github repository https://github.com/AnasImloul/Leetcode-solutions\nIt is very helpful, check it out.\n\nclass Node{\n | Kagoot | NORMAL | 2022-08-29T22:28:50.240961+00:00 | 2022-08-29T22:28:50.241001+00:00 | 92 | false | This is not my answer. I found it in this Github repository https://github.com/AnasImloul/Leetcode-solutions\nIt is very helpful, check it out.\n```\nclass Node{\n constructor(val,parent){\n this.val=val,this.parent=parent,this.children={},this.hash\n }\n}\nclass Trie{\n constructor(){\n this.root=new Node(\'\')\n this.hashMemo={}\n }\n insert(path){\n let cur=this.root\n for(let node of path )\n if(cur.children[node]!==undefined)\n cur=cur.children[node]\n else\n cur.children[node]=new Node(node,cur),\n cur=cur.children[node]\n }\n traverse(node=this.root){\n node.hash=[]\n if(node.children)\n for(let child of Object.values(node.children))\n node.hash.push(this.traverse(child))\n node.hash=node.hash.join(\'~\')\n if(node.hash!==\'\'){\n if(this.hashMemo[node.hash]===undefined)\n this.hashMemo[node.hash]=[] \n this.hashMemo[node.hash].push(node)\n return node.val+\'/[\'+node.hash+\']\'\n }\n return node.val\n }\n delete(node=this.root){\n if(!node || node.hash===undefined)\n return\n else if(this.hashMemo[node.hash] && this.hashMemo[node.hash].length>1)\n for(let todelete of this.hashMemo[node.hash])\n delete todelete.parent.children[todelete.val]\n else\n for(let child of Object.values(node.children))\n this.delete(child)\n }\n serialize(node=this.root,stack=[],res=[]){\n if(node.val!==\'\')\n stack.push(node.val),\n res.push([...stack])\n for(let child of Object.values(node.children))\n this.serialize(child,stack,res)\n stack.pop()\n return res\n }\n}\n\nvar deleteDuplicateFolder = function(paths) {\n let T=new Trie()\n for(let P of paths)\n T.insert(P)\n T.traverse()\n T.delete()\n return T.serialize()\n};\n\n``` | 0 | 0 | ['JavaScript'] | 1 |
delete-duplicate-folders-in-system | Java | Concise | Briefly Explained + Comments | java-concise-briefly-explained-comments-dkvjd | I tried to hash the tree with long but there were hash collision, so I changed it to String.\n\nBasically 3 steps:\n1. Create the tree. It is similar to how one | Student2091 | NORMAL | 2022-08-08T05:25:14.227403+00:00 | 2022-08-08T05:25:43.332073+00:00 | 165 | false | I tried to hash the tree with long but there were hash collision, so I changed it to String.\n\nBasically 3 steps:\n1. Create the tree. It is similar to how one would build a Trie\n2. Hash The Tree with **Post-Order** DFS traversal & mark duplicate subtrees. This is linear time. \n3. DFS again to add all paths that aren\'t marked deleted.\n\nI used a TreeMap to maintain children\'s order.\n#### Java\n```Java\n// 173ms (77% Speed)\n// 69.8 MB (92% Memory)\nclass Solution {\n public List<List<String>> deleteDuplicateFolder(List<List<String>> paths) {\n List<List<String>> ans = new ArrayList<>();\n Tree root = new Tree();\n for (List<String> p : paths){ // build the tree\n Tree cur = root;\n for (String f : p){\n cur.sub.putIfAbsent(f, new Tree());\n cur = cur.sub.get(f);\n cur.name = f;\n }\n }\n mark(root, new HashMap<>()); // hash + mark\n populate(root, new ArrayList<>(), ans); // populate all paths\n return ans;\n }\n\n private String mark(Tree root, Map<String, Tree> seen){\n StringBuilder sb = new StringBuilder("T"); // Start\n for (String key : root.sub.keySet()){\n Tree next = root.sub.get(key);\n sb.append(mark(next, seen)).append("S"); // children separator \n }\n if (seen.containsKey(sb.toString())){ // delete duplicates\n root.deleted=seen.get(sb.toString()).deleted=true;\n }\n if (!root.sub.isEmpty()){ // Leaf node doesn\'t get to compare\n seen.put(sb.toString(), root);\n }\n sb.append("P").append(root.name); // Add itself\n return sb.toString();\n }\n\n private void populate(Tree root, List<String> tmp, List<List<String>> ans){\n if (root.deleted){\n return;\n }\n if (!root.name.isEmpty()){ // add current path\n tmp.add(root.name);\n ans.add(new ArrayList<>(tmp));\n }\n for (String key : root.sub.keySet()){ // recursively add all subpaths \n populate(root.sub.get(key), tmp, ans);\n }\n if (!tmp.isEmpty()){\n tmp.remove(tmp.size()-1);\n }\n }\n\n private class Tree {\n boolean deleted;\n String name = "";\n Map<String, Tree> sub = new TreeMap<>();\n Tree(){}\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
delete-duplicate-folders-in-system | Python Hashmap | python-hashmap-by-dlim-0qzm | Let N, M, and K be the number of folders, sum(len(paths[i])), and the maximum length of folder name respectively.\n1. Make a tree structure from \'paths\'\n | dlim_ | NORMAL | 2022-08-07T22:12:15.231749+00:00 | 2022-09-03T19:59:16.672929+00:00 | 70 | false | Let N, M, and K be the number of folders, sum(len(paths[i])), and the maximum length of folder name respectively.\n1. Make a tree structure from \'paths\'\n time complexity: O(M)\n\tspace compexity O(NK)\n```\nclass Node:\n def __init__(self, val, parent=None, children=None):\n self.val = val\n self.children = {}\n self.group = -1\n self.key = None \n\t\t\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n\t\troot = Node(\'/\')\n\t\tfor path in paths:\n\t\t\tnode = root\n\t\t\tfor name in path:\n\t\t\t\tif name not in node.children:\n\t\t\t\t\tnode.children[name] = Node(name)\n\t\t\t\tnode = node.children[name]\n```\n\n2. To group and count \'identical\' subtrees, use a hashmap. Instead of using the serialized string of each subtree as the key, use tuples of the children\'s group number and children\'s name for the key. Only for the leaf nodes use their name as the key.\n time complexity: O(N log(N)) for sort and O(NK) for making and using keys\n\t\n```\n\t\tumap = dict() \n\t\t\n def dfs(root):\n if not root.children:\n root.key = root.val\n else:\n for child in root.children.values():\n dfs(child)\n root.key = tuple(sorted((child.group, child.val) for child in root.children.values()))\n \n nonlocal umap\n if root.key not in umap:\n umap[root.key] = [len(umap), 1]\n else:\n umap[root.key][1] += 1\n root.group = umap[root.key][0]\n \n dfs(root)\n```\n\n3. Read valid paths by excluding duplicate nodes that are not leaves.\n time complexity: same as in part 2\n```\n def readPaths(root, cand, res):\n nonlocal umap\n for child in root.children.values():\n if umap[child.key][1] == 1 or type(child.key) == str:\n cand.append(child.val)\n res.append(list(cand))\n readPaths(child, cand, res)\n cand.pop()\n \n res = []\n readPaths(root, [], res)\n return res\n```\n\nOverall time complexity: O(M + N log(N) + NK)\nOverall space complexity: O(NK) | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Java | java-by-alsamany-7a0j | class Solution {\n static class Node {\n String name;\n Map childern = new HashMap<>();\n\n private String hashCode = null;\n\n p | alsamany | NORMAL | 2022-08-03T14:27:50.924891+00:00 | 2022-08-03T14:27:50.924923+00:00 | 41 | false | class Solution {\n static class Node {\n String name;\n Map<String, Node> childern = new HashMap<>();\n\n private String hashCode = null;\n\n public Node(String _name) {\n name = _name;\n }\n\n public void add(List<String> path) {\n Node cur = this;\n for (String file : path) {\n if (!cur.childern.containsKey(file)) {\n cur.childern.put(file, new Node(file));\n }\n cur = cur.childern.get(file);\n }\n }\n\n public String getHashCode() {\n if(hashCode == null) {\n hashCode = computeHash();\n }\n\n return hashCode;\n }\n\n private String computeHash() {\n StringBuilder sb = new StringBuilder();\n List<Node> nodes = new ArrayList<>();\n \n for(Node n: childern.values()) {\n nodes.add(n);\n }\n\n if(nodes.size() == 0)\n return null;\n\n nodes.sort((a, b) -> a.name.compareTo(b.name));\n\n for (Node n: nodes){\n sb.append(\'(\');\n sb.append(n.name + n.getHashCode());\n sb.append(\')\');\n }\n\n return sb.toString();\n }\n }\n\n private static void getGoodFiles(Node node, Map<String, Integer> occurs, List<String> cur, List<List<String>> ans) {\n if(occurs.containsKey(node.getHashCode()) && occurs.get(node.getHashCode()) > 1) return;\n\n cur.add(node.name);\n ans.add(new ArrayList<>(cur));\n\n for(Node n: node.childern.values())\n getGoodFiles(n, occurs, cur, ans);\n\n cur.remove(cur.size()-1);\n }\n\n private static void findOccurs(Node node, Map<String, Integer> occurs) {\n String key = node.getHashCode();\n if(key != null) {\n occurs.put(key, occurs.getOrDefault(node.getHashCode(), 0)+1);\n }\n\n for(Node n: node.childern.values()) {\n findOccurs(n, occurs);\n }\n }\n\n\n static Node root;\n\n public static List<List<String>> deleteDuplicateFolder(List<List<String>> paths) {\n root = new Node("");\n for (List<String> path : paths)\n root.add(path);\n\n Map<String, Integer> occurs = new HashMap<>();\n findOccurs(root, occurs);\n for(Map.Entry<String, Integer> e : occurs.entrySet()) {\n System.out.println(e.getKey() + " " + e.getValue());\n }\n\n List<List<String>> ans = new ArrayList<>();\n for(Node n: root.childern.values())\n getGoodFiles(n, occurs, new ArrayList<>(), ans);\n\n return ans;\n }\n} | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Java - Somewhat brute force but beats 80% | java-somewhat-brute-force-but-beats-80-b-54td | The algorithm as 4 parts\n1. Convert the list to a tree\n2. Traverse the tree in post-order manner and generate a unique hash of all the subnodes in the tree. T | cutkey | NORMAL | 2022-07-31T02:14:31.124268+00:00 | 2022-07-31T08:46:37.221286+00:00 | 47 | false | The algorithm as 4 parts\n1. Convert the list to a tree\n2. Traverse the tree in post-order manner and generate a unique hash of all the subnodes in the tree. This is a very important step. The hash is a concatenation of all subnodes under a node. However we need to consider the following\n\t1. Make sure that the children of a node are traversed in a sorted manner as ordering is irrelevant and unless we traverse in a sorted manner we may generate different hashes corresponding to the same set of children for example children [a, b, c, d] should have the same hash as [a, c, b, d]\n\t2. Make sure that you use delimiters while concatinating children labels. Else a->b->c will generate the same hash as a->[b, c].\n3. Map Hashes to a the respective parent. If a Hash has more than one parent mark the parent of deletion\n4. Traverse the tree again to generate the list.\n\n\n```\nclass TreeNode {\n public TreeNode(String label) {\n this.label = label;\n }\n public String label;\n public String hash; \n public boolean deleted;\n // Ordering of child folders is irrelevant so we store in sorted order.\n public TreeMap<String, TreeNode> children = new TreeMap();\n \n @Override \n public int hashCode() { \n return Character.getNumericValue(label.charAt(0)); \n }\n \n public void print(String justification){\n System.out.println(String.format("%s %s: %s", justification, label, hash));\n for (TreeNode node : children.values()){\n node.print(justification+justification);\n }\n }\n}\n\nclass Solution {\n Map<String, List<TreeNode>> map = new HashMap();\n List<List<String>> out = new ArrayList();\n \n public List<List<String>> deleteDuplicateFolder(List<List<String>> paths) {\n TreeNode root = new TreeNode("root");\n for (List<String> path : paths){\n updateTree(root, path, 0);\n }\n \n \n for (TreeNode node : root.children.values()) {\n updateNodeHashCodesMap(node);\n }\n \n // root.print("-");\n \n // for(Map.Entry<String, List<TreeNode>> entry : map.entrySet()){\n // System.out.println(String.format("%s, %s", entry.getKey(), entry.getValue().size()));\n // }\n for (String hashCode : map.keySet()){\n if (map.get(hashCode).size() > 1) {\n for(TreeNode node : map.get(hashCode)){\n node.deleted = true;\n }\n }\n }\n \n for (TreeNode node : root.children.values()) {\n List<LinkedList<String>> lists = getLists(node);\n for (LinkedList<String> list : lists) out.add(list);\n }\n return out;\n }\n \n \n private List<LinkedList<String>> getLists(TreeNode node) {\n List<LinkedList<String>> lists = new ArrayList();\n if (node.deleted) return lists;\n LinkedList<String> base = new LinkedList();\n base.add(node.label);\n lists.add(base);\n for (TreeNode child : node.children.values()){\n List<LinkedList<String>> lsts = getLists(child);\n for(LinkedList lst : lsts){\n lst.add(0, node.label);\n lists.add(lst);\n }\n }\n return lists;\n }\n \n private void updateTree(TreeNode root, List<String> path, int index){\n if (index < path.size()) {\n String label = path.get(index);\n TreeNode node = root.children.getOrDefault(label, new TreeNode(label));\n root.children.put(label, node);\n index++;\n updateTree(node, path, index);\n }\n }\n \n private void updateNodeHashCodesMap(TreeNode node){\n StringBuilder sb = new StringBuilder();\n for (Map.Entry<String, TreeNode> entry: node.children.entrySet()) {\n TreeNode childNode = entry.getValue();\n updateNodeHashCodesMap(childNode);\n sb.append(childNode.label);\n sb.append(childNode.hash);\n // Append a delimiter so that we can differentiate when the subfolders are the same but in different levels.\n sb.append("|");\n \n }\n node.hash = sb.toString();\n if (node.hash != null && node.hash.length() > 0){\n List<TreeNode> nodesWithHashCode = map.getOrDefault(node.hash, new ArrayList());\n nodesWithHashCode.add(node);\n map.put(node.hash, nodesWithHashCode);\n }\n }\n}\n\n\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Golang solution based on trimming | golang-solution-based-on-trimming-by-sam-v8yw | Created a Trie and followed the deletion procedure. \nSince Golang does not have sorted map, it was necessary to sort the keys of children before deduplication\ | sameerpjoshi | NORMAL | 2022-07-24T11:36:22.441424+00:00 | 2022-07-24T11:36:22.441454+00:00 | 56 | false | Created a Trie and followed the deletion procedure. \nSince Golang does not have sorted map, it was necessary to sort the keys of children before deduplication\n``` \nfunc deleteDuplicateFolder(paths [][]string) [][]string {\n \n t := NewTrie()\n for _,path := range paths {\n t.insert(path)\n }\n t.dedupe(t.root,make(map[string]*TrieNode))\n \n ans := [][]string{}\n for _,value := range t.root.children {\n path := []string{}\n t.getPath(value,&path, &ans)\n }\n return ans \n}\n\n\ntype Trie struct {\n root *TrieNode\n}\n\nfunc NewTrie() *Trie {\n node := NewTrieNode("")\n return &Trie{node}\n}\n\n\ntype TrieNode struct {\n name string \n children map[string]*TrieNode\n del bool\n}\n\nfunc NewTrieNode(name string) *TrieNode {\n return &TrieNode{name,make(map[string]*TrieNode),false}\n}\n\nfunc (t *Trie) insert(c []string){\n node := t.root\n for i :=0 ; i < len(c);i++ {\n if child,ok := node.children[c[i]]; ok {\n node = child\n } else {\n child = NewTrieNode(c[i])\n node.children[c[i]] = child\n node = child \n }\n }\n}\n\nfunc (t *Trie) dedupe(node *TrieNode, seen map[string]*TrieNode)string{\n var subfolder string\n keys := make([]string, len(node.children)) \n i := 0\n for k := range node.children {\n keys[i] = k\n i++\n }\n sort.Slice(keys, func(i,j int)bool{\n return keys[i] < keys[j]\n })\n for _,key := range keys {\n subfolder += t.dedupe(node.children[key],seen)\n }\n if len(subfolder) != 0 {\n if priorNode,ok := seen[subfolder]; ok {\n priorNode.del = true\n node.del = true\n } else {\n seen[subfolder] = node \n }\n }\n return "("+node.name+subfolder+")"\n}\n\nfunc (t *Trie) getPath(node *TrieNode, path *[]string, ans *[][]string) {\n if node.del {\n return\n }\n (*path) = append(*path,node.name)\n finalPath := make([]string,len(*path))\n copy(finalPath,(*path))\n (*ans) = append(*ans,finalPath)\n for _,child := range node.children {\n t.getPath(child,path,ans)\n }\n (*path) = (*path)[:len(*path)-1]\n}\n``` | 0 | 0 | ['Go'] | 0 |
delete-duplicate-folders-in-system | C++ Clean & Fast Code with Explanation | Faster than 90% | c-clean-fast-code-with-explanation-faste-7jjz | Firstly, construct a tree which denotes the file system. The value of every tree node is the corresponding folder name.\n\nThen, we compress every node\'s subtr | vampireweekend | NORMAL | 2022-07-12T07:58:17.421783+00:00 | 2022-07-12T07:58:17.421822+00:00 | 77 | false | Firstly, construct a tree which denotes the file system. The value of every tree node is the corresponding folder name.\n\nThen, we compress every node\'s subtree architecture into a string. Note that in order to judge two identical tree nodes, the children of every node should be visited according to the lexigraphical order of their values when compressing the architecture information. Save the subtree strings in a hashmap `cnt` to judge whether their are duplicate ones.\n\nFinally we do a DFS on the tree and do not visit those nodes who share a duplicate subtree architecture to get the results.\n\n```c++\nclass Solution {\npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n constructTree(paths);\n constructSubtreeString(root);\n vector<string> path;\n for (auto child: root->children)\n deleteDup(child.second, path);\n return this->res;\n }\nprivate:\n struct TreeNode{\n string val, subtree = "";\n map<string, TreeNode*> children;\n TreeNode() {}\n TreeNode(string val) {\n this->val = val;\n }\n };\n TreeNode *root;\n unordered_map<string, int> cnt;\n vector<vector<string>> res;\n \n inline void constructTree(vector<vector<string>>& paths) {\n root = new TreeNode();\n for (auto& path: paths) {\n auto cur = root;\n for (auto& name: path) {\n if (!cur->children.count(name))\n cur->children[name] = new TreeNode(name);\n cur = cur->children[name];\n }\n }\n }\n \n inline void constructSubtreeString(TreeNode* cur) {\n for (auto& child: cur->children) {\n constructSubtreeString(child.second);\n cur->subtree += child.first + "[" + child.second->subtree + "]";\n }\n cnt[cur->subtree]++;\n }\n \n inline void deleteDup(TreeNode* cur, vector<string>& path) {\n if (cur->subtree != "" && cnt[cur->subtree] > 1) return;\n path.push_back(cur->val);\n res.push_back(path);\n for (auto& child: cur->children)\n deleteDup(child.second, path);\n path.pop_back();\n }\n};\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Weird Expected output | weird-expected-output-by-jainish-2ydy | Input\n[["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"],["b","w"]]\nOutput\n[["b"],["b","w"]]\nExpected\n[["a"],["b"],["a","z"], | jainish | NORMAL | 2022-07-08T14:00:47.573752+00:00 | 2022-07-08T14:00:47.573792+00:00 | 21 | false | Input\n[["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"],["b","w"]]\nOutput\n[["b"],["b","w"]]\nExpected\n[["a"],["b"],["a","z"],["b","z"],["b","w"]]\n\nSeems according to me that expected sol is wrong .\n\nhere is the sub directory structure \n *\n\t/ \\ \na b\n| \\ | \\ \\ \nx z x z w\n| |\ny y\n\n\nSeems Intutive that the Entire "A" directory should be removed and for "B" only ["b"] and "[b","w"] paths should remain \n\n\nAm I understanding something wrong here ?\n\n | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Python Clean Solution | python-clean-solution-by-user6397p-oe6e | \nclass Trie:\n def __init__(self):\n self.children = defaultdict(Trie)\n self.delete = False\n\nclass Solution:\n def deleteDuplicateFolder | user6397p | NORMAL | 2022-07-06T09:01:45.193272+00:00 | 2022-07-06T09:01:45.193300+00:00 | 175 | false | ```\nclass Trie:\n def __init__(self):\n self.children = defaultdict(Trie)\n self.delete = False\n\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n root = Trie()\n patterns = defaultdict(list)\n ans = []\n\n self.populate_trie(root, paths)\n self.generate_patterns(root, patterns)\n self.update_node_status(patterns)\n self.generate_valid_paths(root, [], ans)\n \n return ans\n \n def populate_trie(self, root, paths):\n for path in sorted(paths):\n node = root\n for c in path:\n node = node.children[c]\n\n def generate_patterns(self, node, patterns):\n pattern = f\'({"".join(child + self.generate_patterns(node.children[child], patterns) for child in node.children)})\'\n\n if pattern != "()":\n patterns[pattern].append(node)\n\n return pattern\n\n def update_node_status(self, patterns):\n for pattern in patterns:\n if len(patterns[pattern]) > 1:\n for node in patterns[pattern]:\n node.delete = True\n\n def generate_valid_paths(self, node, path, ans):\n if path:\n ans.append(path[:])\n \n for child in node.children:\n if not node.children[child].delete:\n self.generate_valid_paths(node.children[child], path + [child], ans)\n``` | 0 | 0 | ['Python3'] | 0 |
delete-duplicate-folders-in-system | C++ || Trie || DFS || Map || (TLE/MLE) | c-trie-dfs-map-tlemle-by-igloo11-5vnf | \nclass Solution {\nprivate:\n map<string, int> cnt;\n \n struct Node {\n string data;\n string directory;\n map<string, Node*> ne | Igloo11 | NORMAL | 2022-05-06T18:17:26.633131+00:00 | 2022-05-06T18:18:27.082333+00:00 | 149 | false | ```\nclass Solution {\nprivate:\n map<string, int> cnt;\n \n struct Node {\n string data;\n string directory;\n map<string, Node*> next;\n Node(string value) {\n data = value;\n directory = "";\n }\n };\n \n void make_directory(Node* root, vector<vector<string>> &ans, vector<string> &path) {\n if(root == NULL)\n return;\n else if(root->directory == "X")\n return;\n path.push_back(root->data);\n ans.push_back(vector<string>(path));\n for(auto it: root->next) {\n if(it.second->directory != "X") {\n make_directory(it.second, ans, path);\n path.pop_back();\n }\n } \n }\n \n void remove_duplicates(Node* root) {\n if(root == NULL) \n return;\n if(cnt[root->directory] > 1) {\n // value X determines it wouldn\'t be included\n // cout << cnt[root->directory] << "-" << root->directory << endl;\n root->directory = "X";\n }\n for(auto it: root->next) {\n remove_duplicates(it.second);\n }\n }\n \n string mark_duplicates(Node* root) {\n if(root == NULL)\n return "X";\n string directory = "";\n for(auto it: root->next) {\n directory = directory + mark_duplicates(it.second);\n\t\t\t// note: used ordered map\n // why this line is added?? see the given testcase\n directory += "/";\n }\n root->directory = directory;\n if(directory.length() > 0)\n cnt[directory] += 1;\n return root->data + "/" + directory;\n }\n \n void create_tree(Node* root, vector<string> &path) {\n Node* curr = root;\n for(string name: path) {\n Node* node = curr->next[name];\n if(node == NULL) {\n node = new Node(name);\n curr->next[name] = node;\n }\n curr = node;\n }\n }\n \n \npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n Node* root = new Node("/");\n for(vector<string> path: paths)\n create_tree(root, path);\n \n mark_duplicates(root);\n remove_duplicates(root);\n \n vector<vector<string>> ans;\n vector<string> path;\n for(auto it: root->next) {\n make_directory(it.second, ans, path);\n path.clear();\n }\n \n return ans;\n }\n \n // ambiguity of this testcase while using ordered map\n // [["a"],["a","c"],["a","d"],["a","d","e"],["b"],["b","e"],["b","c"],["b","c","d"],["f"],["f","h"],["f","h","i"],["f","j"],["g"],["g","j"],["g","h"],["g","h","i"]]\n};\n``` | 0 | 0 | ['Depth-First Search', 'Trie', 'C'] | 0 |
delete-duplicate-folders-in-system | [C++] Trie + DFS hashing | c-trie-dfs-hashing-by-kaminyou-frkx | \nclass TrieNode {\npublic:\n map<string, TrieNode*> children;\n bool isEnd;\n bool isExcluded;\n string name;\n TrieNode(string folder) {\n | kaminyou | NORMAL | 2022-04-28T15:22:20.354868+00:00 | 2022-04-28T15:22:20.354897+00:00 | 178 | false | ```\nclass TrieNode {\npublic:\n map<string, TrieNode*> children;\n bool isEnd;\n bool isExcluded;\n string name;\n TrieNode(string folder) {\n name = folder;\n isEnd = false;\n isExcluded = false;\n }\n};\nclass Trie {\npublic:\n TrieNode* root;\n Trie() {\n root = new TrieNode("/");\n }\n void insert(vector<string>& path) {\n int n = path.size();\n TrieNode* curr = root;\n for (int i = 0; i < n; i++) {\n if (curr->children.find(path[i]) == curr->children.end()) {\n curr->children[path[i]] = new TrieNode(path[i]);\n }\n curr = curr->children[path[i]];\n }\n curr->isEnd = true;\n }\n void findDuplicate(unordered_map<string, vector<TrieNode*>>& mp) {\n hashAndStore(root, mp);\n }\n string hashAndStore(TrieNode* node, unordered_map<string, vector<TrieNode*>>& mp) {\n string curr = "";\n for (auto child : node->children) {\n curr += hashAndStore(child.second, mp);\n curr.push_back(\'|\');\n }\n if (curr != "") mp[curr].push_back(node);\n return node->name + "|" + curr;\n }\n void markDuplicate(unordered_map<string, vector<TrieNode*>>& mp) {\n for (auto element : mp) {\n if (element.second.size() > 1) {\n for (auto node : element.second) {\n node->isExcluded = true;\n }\n }\n }\n }\n void getNotDuplicate(vector<vector<string>>& ans, vector<string>& path) {\n _getNotDuplicate(root, ans, path);\n }\n void _getNotDuplicate(TrieNode* node, vector<vector<string>>& ans, vector<string>& path) {\n if (node->isExcluded) return;\n if (node->isEnd) ans.push_back(path);\n for (auto child : node->children) {\n path.push_back(child.second->name);\n _getNotDuplicate(child.second, ans, path);\n path.pop_back();\n }\n }\n};\nclass Solution {\npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n Trie* trie = new Trie();\n for (auto path : paths) trie->insert(path);\n \n unordered_map<string, vector<TrieNode*>> mp;\n trie->findDuplicate(mp);\n trie->markDuplicate(mp);\n \n vector<vector<string>> ans;\n vector<string> path;\n trie->getNotDuplicate(ans, path);\n return ans;\n }\n};\n``` | 0 | 0 | ['Depth-First Search', 'Trie', 'C'] | 0 |
delete-duplicate-folders-in-system | Swift Solution | swift-solution-by-maksimilliano-v6z6 | \nclass Solution {\n private var subdirsTotal: [String: Bool] = [:]\n \n func deleteDuplicateFolder(_ paths: [[String]]) -> [[String]] {\n var root = Node | maksimilliano | NORMAL | 2022-04-08T16:55:35.661148+00:00 | 2022-04-08T16:55:35.661192+00:00 | 50 | false | ```\nclass Solution {\n private var subdirsTotal: [String: Bool] = [:]\n \n func deleteDuplicateFolder(_ paths: [[String]]) -> [[String]] {\n var root = Node(value: "/")\n for path in paths {\n let oldRoot = root\n createTree(path, &root)\n root = oldRoot\n }\n \n marker(root)\n \n var result: [[String]] = []\n var temp: [String] = []\n \n getTheResult(&result, &temp, root)\n \n return result\n }\n \n private func getTheResult(_ result: inout [[String]], _ temp: inout [String], _ root: Node) {\n for child in root.childs {\n if subdirsTotal[child.subdirs] != true {\n temp.append(child.value)\n result.append(temp)\n getTheResult(&result, &temp, child)\n temp.removeLast()\n }\n }\n }\n \n private func marker(_ root: Node) -> String {\n var temp: [String] = []\n let sorted = root.childs.sorted(by: { $0.value > $1.value })\n for value in sorted {\n let sub = marker(value)\n temp.append(sub)\n }\n let str = temp.map { "(\\($0))" }.joined(separator: "")\n \n root.subdirs = str\n if subdirsTotal[str] != nil && temp.count > 0 {\n subdirsTotal[str] = true\n } else {\n subdirsTotal[str] = false\n }\n return "(\\(str + root.value))"\n }\n \n private func createTree(_ path: [String], _ root: inout Node) {\n for i in 0..<path.count {\n if root.childs.first(where: {$0.value == path[i]}) == nil {\n let node = Node(value: path[i])\n root.childs.append(node)\n }\n if let node = root.childs.first(where: {$0.value == path[i]}) {\n root = node\n }\n }\n }\n \n private class Node: Hashable {\n var value: String\n var childs: [Node] = []\n var subdirs: String = ""\n \n init(value: String) {\n self.value = value\n }\n \n static func == (lhs: Solution.Node, rhs: Solution.Node) -> Bool {\n lhs.value == rhs.value\n }\n \n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n }\n}\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Short but slow js solution | short-but-slow-js-solution-by-837951602-1yii | Runtime: 1446 ms\nMemory Usage: 96.1 MB\n\nvar deleteDuplicateFolder = function(paths) {\n var root = {}, socks = {};\n paths.sort().forEach(x=>x.reduce(( | 837951602 | NORMAL | 2022-02-27T17:52:19.993208+00:00 | 2022-02-27T17:52:19.993243+00:00 | 101 | false | Runtime: 1446 ms\nMemory Usage: 96.1 MB\n```\nvar deleteDuplicateFolder = function(paths) {\n var root = {}, socks = {};\n paths.sort().forEach(x=>x.reduce((dir,v)=>dir[v]||(dir[v]={}),root));\n function f(folder) {\n var n = JSON.stringify(folder);\n socks[n] = -~socks[n];\n for (var i in folder) f(folder[i]);\n }\n paths = [];\n function g(folder, p) {\n for (var i in folder) {\n if (socks[JSON.stringify(folder[i])]>1) {\n delete folder[i];\n } else {\n var q = p.concat(i);\n paths.push(q);\n g(folder[i], q);\n }\n }\n }\n f(root);\n socks[\'{}\'] = 0;\n g(root, []);\n return paths;\n};\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Clean Python Solution (Self-Explained, Easy to Understand) | clean-python-solution-self-explained-eas-i0ot | python\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.key = None\n self.children = {}\n\nclass Solution(object) | christopherwu0529 | NORMAL | 2022-01-21T03:00:44.649034+00:00 | 2022-01-21T03:37:58.939815+00:00 | 261 | false | ```python\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.key = None\n self.children = {}\n\nclass Solution(object):\n def deleteDuplicateFolder(self, paths):\n def setKey(node):\n node.key = \'\'\n for c in sorted(node.children.keys()): #need to be sorted. so when child structs are the same, we won\'t generate different key from different iteration order.\n setKey(node.children[c])\n node.key += node.children[c].val + \'|\' + node.children[c].key + \'|\' #generate a key for each node. only considering its children structure. (see the "identical" definition, it does not consider the val of the node itself.)\n \n keyCount[node.key] += 1\n \n def addPath(node, path):\n if node.children and keyCount[node.key]>1: return #leaf node does not apply to this rule\n ans.append(path+[node.val])\n for c in node.children:\n addPath(node.children[c], path+[node.val])\n \n \n ans = []\n root = Node(\'/\')\n keyCount = collections.Counter()\n \n #build the tree\n for path in paths:\n node = root\n for c in path:\n if c not in node.children: node.children[c] = Node(c)\n node = node.children[c]\n \n #set all nodes key recursively\n setKey(root)\n\n #build ans\n for c in root.children:\n addPath(root.children[c], [])\n \n return ans\n\t\t\n"""\nFor interview preparation, similar problems, check out my GitHub.\nIt took me a lots of time to make the solution. Becuase I want to help others like me.\nPlease give me a star if you like it. Means a lot to me.\nhttps://github.com/wuduhren/leetcode-python\n"""\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | Ugly unoptimised Ruby solution, still beats 100%/100% | ugly-unoptimised-ruby-solution-still-bea-22ww | \n# @param {String[][]} paths\n# @return {String[][]}\ndef delete_duplicate_folder(paths)\n root = {}\n paths.sort.each do |path|\n cur = root\n path.ea | dnnx | NORMAL | 2021-12-11T22:07:31.104038+00:00 | 2021-12-11T22:07:31.104061+00:00 | 87 | false | ```\n# @param {String[][]} paths\n# @return {String[][]}\ndef delete_duplicate_folder(paths)\n root = {}\n paths.sort.each do |path|\n cur = root\n path.each do |name|\n cur = (cur[name] ||= {})\n end\n end\n \n @mem = Hash.new { |h, k| h[k] = [] }\n f([], root) \n @mem.keep_if { |k, v| v.size > 1 && !k.empty? }\n @mem.values.flatten(1).each do |*path, name|\n cur = root\n path.each do |nm|\n cur = cur[nm]\n break unless cur\n end\n next unless cur\n cur.delete(name)\n end\n g([], root)\nend\n\n\ndef g(path, node)\n node.flat_map do |name, subnode|\n pp = path + [name]\n [pp] + g(pp, subnode)\n end\nend\n\ndef f(path, node)\n @mem[node] << path\n node.each { |name, subnode| f(path + [name], subnode) }\nend\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | [python] dfs with trie | python-dfs-with-trie-by-vl4deee11-18ni | \nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n tr={"1":"*"}\n for p in paths:\n c | vl4deee11 | NORMAL | 2021-09-27T06:15:59.010629+00:00 | 2021-09-27T06:15:59.010658+00:00 | 244 | false | ```\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n tr={"1":"*"}\n for p in paths:\n ctr=tr\n for f in p:\n if f not in ctr:\n ctr[f]={"1":f} \n ctr=ctr[f]\n hm=defaultdict(list)\n def dfs(p,n):\n if not n:return ""\n h,i=[],0\n for k in sorted(n.keys()):\n if k!="1":\n h.append(f\'{dfs(n,n[k])}{i}\')\n i+=1\n h="".join(h)\n hm[h].append((p,n["1"]))\n return h+n["1"]\n \n dfs({},tr)\n del hm[""]\n for x in hm:\n if len(hm[x])>1:\n for p,f in hm[x]:del p[f]\n res=[]\n def dfs2(n,p):\n if not n:return\n res.append(p)\n for k in n:\n if k!="1":dfs2(n[k],p+[k])\n \n dfs2(tr,[])\n return res[1:]\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | [Simple & Efficient][C++] Trie + Hashing | simple-efficientc-trie-hashing-by-outvoi-w85b | \nclass Solution {\n\tusing ull = unsigned long long;\n\n\tstruct hash_t {\n\t\tstatic constexpr ull base = 31, begin = 27, end = 28;\n\t\tull value, coeff;\n\t | outvoider | NORMAL | 2021-08-15T23:45:14.362042+00:00 | 2021-08-20T07:14:26.539541+00:00 | 309 | false | ```\nclass Solution {\n\tusing ull = unsigned long long;\n\n\tstruct hash_t {\n\t\tstatic constexpr ull base = 31, begin = 27, end = 28;\n\t\tull value, coeff;\n\t\thash_t() : value(0), coeff(1) {}\n\t\thash_t(ull value, ull coeff) : value(value), coeff(coeff) {}\n\t\thash_t(string_view s) : hash_t() {\n\t\t\tfor (char c : s)\n\t\t\t\taggregate({ ull(c - \'a\' + 1), base });\n\t\t}\n\t\tvoid aggregate(hash_t that) {\n\t\t\tvalue = that.coeff * value + that.value;\n\t\t\tcoeff *= that.coeff;\n\t\t}\n\t};\n\n\tstruct folder_t {\n\t\thash_t hash, name_hash;\n\t\tvector<string>* path;\n\t\tmap<ull, folder_t> children;\n\n\t\tvoid create_folders(vector<vector<string>>& paths) {\n\t\t\tfor (auto& path : paths) {\n\t\t\t\tauto* current = this;\n\t\t\t\tfor (const auto& folder : path) {\n\t\t\t\t\thash_t name_hash{ folder };\n\t\t\t\t\tcurrent = ¤t->children[name_hash.value];\n\t\t\t\t\tcurrent->name_hash = name_hash;\n\t\t\t\t}\n\t\t\t\tcurrent->path = &path;\n\t\t\t}\n\t\t\tpath = nullptr;\n\t\t}\n\n\t\tvoid compute_hashes(unordered_map<ull, int> &hash_to_count) {\n\t\t\thash.aggregate({ hash_t::begin, hash_t::base });\n\t\t\tfor (auto& child : children) {\n\t\t\t\tchild.second.compute_hashes(hash_to_count);\n\t\t\t\thash.aggregate(child.second.name_hash);\n\t\t\t\thash.aggregate(child.second.hash);\n\t\t\t}\n\t\t\thash.aggregate({ hash_t::end, hash_t::base });\n\t\t\tif (children.size() != 0)\n\t\t\t\t++hash_to_count[hash.value];\n\t\t}\n\n\t\tvoid compute_paths(unordered_map<ull, int>& hash_to_count, unordered_set<vector<string>*>& paths_to_keep) {\n\t\t\tif (hash_to_count[hash.value] > 1)\n\t\t\t\treturn;\n\t\t\tif (path != nullptr)\n\t\t\t\tpaths_to_keep.insert(path);\n\t\t\tfor (auto& child : children)\n\t\t\t\tchild.second.compute_paths(hash_to_count, paths_to_keep);\n\t\t}\n\t};\n\npublic:\n\tvector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n\t\tfolder_t root;\n\t\tunordered_map<ull, int> hash_to_count;\n\t\tunordered_set<vector<string>*> paths_to_keep;\n\t\troot.create_folders(paths);\n\t\troot.compute_hashes(hash_to_count);\n\t\troot.compute_paths(hash_to_count, paths_to_keep);\n\t\tpaths.erase(remove_if(paths.begin(), paths.end(), [&](auto& path) { return paths_to_keep.count(&path) == 0; }), paths.end());\n\t\treturn paths;\n\t}\n};\n``` | 0 | 0 | [] | 0 |
delete-duplicate-folders-in-system | C++ Solution O(nlogn) solution by assigning ids to serializations | c-solution-onlogn-solution-by-assigning-q39fe | \nclass Solution {\n struct Node {\n string val;\n bool skip = false;\n unordered_map<string, Node*> next;\n Node() = default;\n | yeetcode_t | NORMAL | 2021-08-05T11:51:05.481303+00:00 | 2021-08-05T11:51:05.481337+00:00 | 262 | false | ```\nclass Solution {\n struct Node {\n string val;\n bool skip = false;\n unordered_map<string, Node*> next;\n Node() = default;\n Node(string v) : val{move(v)} {};\n }; \n unordered_map<string, pair<int, Node*>> tree_map;\n unordered_map<string, Node*> content_map;\n int count = 1;\n \n int dfs(Node* n) {\n vector<int> ids;\n for(auto p : n->next) ids.push_back(dfs(p.second));\n sort(ids.begin(), ids.end());\n string tree_key = n->val;\n string content_key;\n for(auto id : ids) content_key.append("," + to_string(id));\n tree_key.append(content_key);\n auto [it, ins] = tree_map.try_emplace(tree_key, make_pair(count, n));\n if(ins) ++count;\n if(!ids.empty()) {\n auto [it2, ins2] = content_map.try_emplace(content_key, n);\n if(!ins2) {\n n->skip = true;\n it2->second->skip = true;\n }\n }\n return it->second.first;\n }\n vector<vector<string>> ans;\n void get_paths(Node* n, vector<string>& path) {\n if(n->skip) return;\n path.push_back(move(n->val));\n ans.push_back(path);\n for(auto p : n->next) get_paths(p.second, path);\n path.pop_back();\n }\npublic:\n vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {\n // create the tree \n auto root = new Node();\n for(auto v : paths) {\n auto curr = root;\n int i = 0;\n for(auto k : v) {\n if(curr->next.find(k) == curr->next.end()) curr->next[k] = new Node(k);\n curr = curr->next[k];\n }\n }\n dfs(root);\n vector<string> path;\n for(auto p : root->next) get_paths(p.second, path);\n return ans;\n }\n};\n\n``` | 0 | 0 | [] | 0 |
maximum-number-of-k-divisible-components | Why greedy dfs will work? Easiest Intution explanation! | why-greedy-dfs-will-work-easiest-intutio-g26f | Intuition\n Describe your first thoughts on how to solve this problem. \n#### Let\'s understand the problem first:\n- Nodes represent undirected (tree)\n- To re | IndominouS | NORMAL | 2023-10-02T13:59:38.167351+00:00 | 2024-08-31T14:20:18.581333+00:00 | 1,412 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n#### Let\'s understand the problem first:\n- Nodes represent undirected (tree)\n- To return max no of components divisible by k\n\n###### Now how can we form a component whose sum is divisible by k?\n> Isn\'t this similar to finding a sub-tree whose sum equals to target? \n\n> Traverse the whole tree and when you reach leaf nodes start returning values and as you come up in recursion stack check the condition whether the current sum % k == 0.\n\n###### Now other problem comes to be how to give max no. of components?\n> First thought : dp? Like we can try all the possible combinations of components whether to choose this component or will it connect with other component and give us better solution? or (if i choose this component will the remaining tree be valid)?\n\n> Dp covers all the cases and after memoization it can give you n^2 solution too.\n\n###### Can we do this greedily? (I always pop this q in my mind)\n> To think of greedily try to solve the cases of dp whether they are true for all?\n\n> Like choosing the component that is divisble by k will leave the remaining tree valid?\n```\nIn the constraints it is written that sum of values array \n(which represents the value of tree nodes) is divisble by k.\n\n(node1 + node2 + node3 + ..... node-n) % k == 0 or\n(node1 + node2 + node3 + ..... node-n) == x*k \n\n- x & y is random factor, \n- (node-r1,r2,r3) depicts node of random subtree)\n\nso if a component is divisible by k this means:\n(node-r1 + node-r2 + node-r3) == y*k \n\nso if you choose this random component and subtract from tree\n\n(node1+node2...node-n) - (node-r1+node-r2+node-r3) = xk - yk\n(node1+node2...node-n) - (node-r1+node-r2+node-r3) = (x-y)*k\n\nhence, remaining tree sum = (x-y)*k % k == 0 (true right?)\n```\n> ##### From the above code block we get 2 observations:\n> - ###### The remaining tree will be valid even if remove the divisible component\n> - We can remove as many components of tree divisible by k as the remaining tree will always be divisible by k (by above obs.).\n\n> Hence there is no need for "not choosing condition" and we can convert this to greedy solution in whicih we will choose the component as soon as we find one and remove from the current tree while increasing our component count.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n###### As the problem says we have an undirected tree which means:\n> We have a single component graph\n\n> Each edge is connected to other edge (some directly some indirectly as edges are undirected)\n\n> ##### Hence above points make this a normal dfs:\n> - ###### we won\'t need to run loop over each vertice and do dfs as it is a single component and,\n> - each edge is connected to other edge hence doesn\'t matter who source is we can start from anywhere and traverse the whole tree.\n# PseudoCode\n```\n- Initialize adjacency list and visited set\n- Make funciton dfs\n- initialize base case (if visited return 0)\n- calculate answers for all child/neighbors for each node\n- now check whether answer is divisble by k\n- if yes: return 0 and increase component count\n- if no: just return the calculated ans for subtree\n```\n\n# Complexity\n- Time complexity: O(V)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(V)\n```\nunresolved space comp: O(V + 2E(for adj list) + V(for set))\nfor tree: E <= V-1 so sc: O(4V - 2) or O(V)\n```\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n adj = defaultdict(list)\n src = 0\n for u,v in edges:\n adj[u].append(v)\n adj[v].append(u)\n comp = 0\n visited = set()\n def dfs(root):\n nonlocal comp\n if root in visited:\n return 0\n visited.add(root)\n ans = values[root]\n for neigh in adj[root]:\n ans += dfs(neigh)\n if ans % k == 0:\n comp += 1\n return 0\n return ans % k\n dfs(src)\n return comp\n```\n```java []\nclass Solution {\n private Map<Integer, List<Integer>> adj;\n private Set<Integer> visited;\n private int comp;\n\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n adj = new HashMap<>();\n visited = new HashSet<>();\n comp = 0;\n\n int src = 0;\n\n for (int[] edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj.computeIfAbsent(u, k1 -> new ArrayList<>()).add(v);\n adj.computeIfAbsent(v, k1 -> new ArrayList<>()).add(u);\n }\n\n dfs(src, values, k);\n return comp;\n }\n\n private int dfs(int root, int[] values, int k) {\n if (visited.contains(root)) {\n return 0;\n }\n\n visited.add(root);\n int ans = values[root];\n\n for (int neigh : adj.getOrDefault(root, Collections.emptyList())) {\n ans += dfs(neigh, values, k);\n }\n\n if (ans % k == 0) {\n comp++;\n return 0;\n }\n\n return ans % k;\n }\n}\n```\n```cpp []\nclass Solution {\nprivate:\n unordered_map<int, vector<int>> adj;\n unordered_set<int> visited;\n int comp;\n\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n comp = 0;\n\n int src = 0;\n\n for (const vector<int>& edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n\n dfs(src, values, k);\n return comp;\n }\n\nprivate:\n int dfs(int root, vector<int>& values, int k) {\n if (visited.count(root)) {\n return 0;\n }\n\n visited.insert(root);\n int ans = values[root];\n\n for (int neigh : adj[root]) {\n ans += dfs(neigh, values, k);\n }\n\n if (ans % k == 0) {\n comp++;\n return 0;\n }\n\n return ans % k;\n }\n};\n```\n## Improved Space complexity Code:\n> As the nodes form a tree hence we just need to stop the nodes from going back to their parents and don\'t actually need a set for that just a condition will do.\n``` python []\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n adj = defaultdict(list)\n src = 0\n for u,v in edges:\n adj[u].append(v)\n adj[v].append(u)\n comp = 0\n def dfs(root,parent):\n nonlocal comp\n ans = values[root]\n for neigh in adj[root]:\n if parent != neigh:\n ans += dfs(neigh,root)\n if ans % k == 0:\n comp += 1\n return 0\n return ans % k\n dfs(src,-1)\n return comp\n```\n``` java []\nimport java.util.*;\n\nclass Solution {\n private Map<Integer, List<Integer>> adj;\n private int comp;\n\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n adj = new HashMap<>();\n comp = 0;\n\n int src = 0;\n\n for (int[] edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj.computeIfAbsent(u, k1 -> new ArrayList<>()).add(v);\n adj.computeIfAbsent(v, k1 -> new ArrayList<>()).add(u);\n }\n\n dfs(src, -1, values, k);\n return comp;\n }\n\n private int dfs(int root, int parent, int[] values, int k) {\n int ans = values[root];\n\n for (int neigh : adj.getOrDefault(root, Collections.emptyList())) {\n if (parent != neigh) {\n ans += dfs(neigh, root, values, k);\n }\n }\n\n if (ans % k == 0) {\n comp++;\n return 0;\n }\n\n return ans % k;\n }\n}\n```\n```cpp []\nclass Solution {\nprivate:\n unordered_map<int, vector<int>> adj;\n int comp;\n\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n comp = 0;\n\n int src = 0;\n\n for (const vector<int>& edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n\n dfs(src, -1, values, k);\n return comp;\n }\n\nprivate:\n int dfs(int root, int parent, vector<int>& values, int k) {\n int ans = values[root];\n\n for (int neigh : adj[root]) {\n if (parent != neigh) {\n ans += dfs(neigh, root, values, k);\n }\n }\n\n if (ans % k == 0) {\n comp++;\n return 0;\n }\n\n return ans % k;\n }\n};\n\n```\n### Please upvote if you like the post. \uD83D\uDE0A\n\n | 28 | 0 | ['Math', 'Dynamic Programming', 'Greedy', 'C++', 'Java', 'Python3'] | 5 |
maximum-number-of-k-divisible-components | ✅[Python] cut leaf or merge with parent (explained) | python-cut-leaf-or-merge-with-parent-exp-zv41 | If a leaf\'s value is divisible by k, we can safely separate it from the tree, thus, increasing the number of components. If not, it will be a part of its paren | stanislav-iablokov | NORMAL | 2023-09-30T16:01:30.498995+00:00 | 2023-09-30T16:15:30.612988+00:00 | 1,766 | false | If a leaf\'s value is divisible by `k`, we can safely separate it from the tree, thus, increasing the number of components. If not, it will be a part of its parent\'s component. To account for the latter, it is sufficient to just increase the parent\'s value by the leaf\'s value. \n\nThe algorithm proceeds by cutting leafs at each step and either cutting them (if they correspond to correct components) or merging them with parents (if not).\n\n```python\nclass Solution:\n def maxKDivisibleComponents(self, n, edges, values, k) -> int:\n\n if n <= 1 : return 1\n \n count = 0\n\n # build adjacency map\n G = defaultdict(set)\n for u,v in edges: G[u].add(v), G[v].add(u)\n \n # start with leaves\n Q = deque(u for u, vs in G.items() if len(vs) == 1)\n \n # cut leaves layer by layer\n while Q:\n for _ in range(len(Q)):\n u = Q.popleft()\n \n # get u\'s parent and remove u from its children\n p = next(iter(G[u])) if G[u] else -1\n if p >= 0 : G[p].remove(u)\n \n # either separate a correct component or add to parent\n if values[u] % k == 0 : count += 1\n else : values[p] += values[u]\n\n # update queue with new leaves\n if p >= 0 and len(G[p]) == 1 : Q.append(p)\n\n return count\n``` | 28 | 0 | ['Python3'] | 6 |
maximum-number-of-k-divisible-components | DFS/topo sort finds components||79 ms Beats 98.73% | dfs-finds-components-by-anwendeng-x39e | Intuition1st approach is DFS which is quite standard.Later try other approach. BFS is doable, but it's a modification of Kahn's algorithm (topo sort) applied to | anwendeng | NORMAL | 2024-12-21T00:56:48.225173+00:00 | 2024-12-21T10:05:21.879236+00:00 | 7,632 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
1st approach is DFS which is quite standard.
Later try other approach. BFS is doable, but it's a modification of Kahn's algorithm (topo sort) applied to undirected tree.
# DFS Approach
<!-- Describe your approach to solving the problem. -->
1. Declare `ans=0, adj (2D vector) visited (bitset` as member variable
2. Define `build_adj` to build adjacent list
3. Define `dfs(int i, vector<int>& values, int k)` to compute the component sum (mod k) & number for components. If you look carefully that the component sum (mod k) is added from the leaf nodes on. In fact the summing way might be by used topologigical sort.
4. In `maxKDivisibleComponents` apply `build_adj(n, edges, values)` & `dfs(0, values, k)`
5. return `ans`
6. Thanks to the mentioning by @hbk73, a slight version for DFS using parameter `parent` instead of `visited` is done.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$O(n)$
# Code DFS||C++ 79 ms Beats 98.73%| DFS with parent 88ms
```cpp []
class Solution {
public:
int ans=0;
vector<vector<int>> adj;
bitset<30001> visited=0;
inline void build_adj(int n, vector<vector<int>>& edges, vector<int>& values)
{
for(auto& e: edges){
int i=e[0], j=e[1];
adj[i].push_back(j);
adj[j].push_back(i);
}
}
inline long long dfs(int i, vector<int>& values, int k){
visited[i]=1;
long long sum=values[i];
for (int j: adj[i]){
if (visited[j]) continue;
sum+=dfs(j, values, k);
sum%=k;
}
if (sum%k==0){
ans++;
return 0;
}
return sum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k)
{
adj.resize(n);
build_adj(n, edges, values);
dfs(0, values, k);
return ans;
}
};
auto init = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
```
```cpp [C++ DFS with parent]
class Solution {
public:
int ans=0;
vector<vector<int>> adj;
inline void build_adj(int n, vector<vector<int>>& edges, vector<int>& values)
{
for(auto& e: edges){
int i=e[0], j=e[1];
adj[i].push_back(j);
adj[j].push_back(i);
}
}
inline int dfs(int i, int parent, vector<int>& values, int k){
int sum=values[i];
for (int j: adj[i]){
if (j==parent) continue;
sum+=dfs(j, i, values, k);
sum%=k;
}
if (sum%k==0){
ans++;
return 0;
}
return sum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k)
{
adj.resize(n);
build_adj(n, edges, values);
dfs(0, -1, values, k);
return ans;
}
};
auto init = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
```
# Toplogical sort
There is a standard method called Kahn algorithm for directed acyclic graph which can solve the Leetcode hard question [1203. Sort Items by Groups Respecting Dependencies](https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/solutions/3933825/c-using-bfs-kahn-s-algorithm-vs-dfs-beats-97-67/).
[Please turn on English subtitles if necessary]
[https://youtu.be/vdar3a_ZdCI?si=VebXKLeqNDe08ydy](https://youtu.be/vdar3a_ZdCI?si=VebXKLeqNDe08ydy)
**Not much different from Kahn's algorithm for DAG**, push all degree 1 vertices to queue `q`(i.e. leaf nodes); then during the iteration, remove the edge `(i, j)`, if the adjacent j becomes to a leaf push j to `q`
# C++ code using topological sort
```
// Build adjacency list and degree array
vector<int> deg;
inline void build_adj(int n, vector<vector<int>>& edges) {
adj.resize(n);
deg.assign(n, 0);
for (auto& e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
deg[u]++;// count degree
deg[v]++;// count degree
}
}
// BFS to count k-divisible components
inline void bfs(vector<int>& values, int k, int n) {
queue<int> q;
// Start with leaf nodes
for (int i = 0; i < n; i++) {
if (deg[i]==1) // Leaf node
q.push(i);
}
while (!q.empty()) {
int i= q.front();// i is a leaf
q.pop();
deg[i]--;//deg[i]=0 visited
if (values[i]%k==0) ans++;// 1 more component
for (int j: adj[i]) {
if (deg[j]==0) continue;
// Propagate modular sum to the adjacent j
values[j] += values[i];
values[j] %= k;
// Remove i, push to queue if it becomes a leaf
if (--deg[j]==1)
q.push(j);
}
}
}
``` | 26 | 1 | ['Depth-First Search', 'Breadth-First Search', 'Topological Sort', 'C++'] | 6 |
maximum-number-of-k-divisible-components | BFS | bfs-by-votrubac-hz1u | As usual, we frist generate the adjacency list from the edges.\n\nThen, we count edges for each node, and we do BFS starting from leaves.\n\nAs we process the n | votrubac | NORMAL | 2023-09-30T16:01:51.297454+00:00 | 2023-09-30T16:12:31.224789+00:00 | 1,951 | false | As usual, we frist generate the adjacency list from the edges.\n\nThen, we count edges for each node, and we do BFS starting from leaves.\n\nAs we process the node `i`, we check if the value is divisible by `k`.\n\nIf so, we can make a cut here, and we increment the result.\n\nThen, for the parent node `j`:\n- we add the value of node `i` (`values[j] += values[i]`)\n- we decrement the number of edges\n- if the number of edges is zero, node `j` is now a leaf, so we add it to the queue.\n\n**C++**\n```cpp\nint maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n vector<vector<int>> al(n);\n vector<int> cnt(n);\n int res = 0;\n for(const auto &e : edges) {\n al[e[0]].push_back(e[1]);\n al[e[1]].push_back(e[0]); \n }\n queue<int> q;\n for (int i = 0; i < n; ++i) {\n cnt[i] = al[i].size();\n if (cnt[i] < 2)\n q.push(i);\n }\n while(!q.empty()) {\n int i = q.front(); q.pop();\n --cnt[i];\n res += values[i] % k == 0;\n for (auto j : al[i]) {\n if (cnt[j] != 0) {\n values[j] += values[i] % k;\n if (--cnt[j] == 1)\n q.push(j);\n }\n }\n }\n return res;\n}\n``` | 26 | 0 | [] | 10 |
maximum-number-of-k-divisible-components | DFS| Prefix Sum| Easy to understand | dfs-prefix-sum-easy-to-understand-by-md_-m0b8 | Intuition\ngo till bottom and then compe up calculating sum of value of nodes\n\n\n\n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. | Md_Rafiq | NORMAL | 2023-09-30T16:12:14.877874+00:00 | 2023-09-30T16:12:14.877894+00:00 | 3,649 | false | # Intuition\ngo till bottom and then compe up calculating sum of value of nodes\n\n\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n // dp array to which is storing the sum of descents including node value\n vector<int> dp;\n int cnt; \n int dfs(vector<int> adj[],int s,vector<int>&vis,vector<int>& values,int k){\n vis[s]=1;\n for(auto nbr:adj[s]){\n if(!vis[nbr]){\n dp[s]+=dfs(adj,nbr,vis,values,k);\n }\n }\n // going from bottom then coming up\n // if sum till current node is divible by k count in ans and return 0;\n if(dp[s]%k==0){\n cnt++;\n return 0;\n }\n \n return dp[s];\n }\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n cnt=0;\n dp.resize(n,0);\n for(int i=0;i<n;i++){\n dp[i]=values[i];\n }\n vector<int> adj[n];\n for(auto e:edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n vector<int> vis(n,0);\n dfs(adj,0,vis,values,k);\n \n return cnt;\n \n \n }\n};\n``` | 25 | 2 | ['Depth-First Search', 'Graph', 'C++'] | 5 |
maximum-number-of-k-divisible-components | Topological Sort Approach ✅| C++ | Java | Python | JavaScript | topological-sort-approach-c-java-python-s98ti | ⬆️Upvote if it helps ⬆️Connect with me on Linkedin [Bijoy Sing]Solution in C++, Python, Java, and JavaScriptIntuitionThe problem can be approached by considerin | BijoySingh7 | NORMAL | 2024-12-21T02:32:30.864398+00:00 | 2024-12-21T02:32:30.864398+00:00 | 8,577 | false | # ⬆️Upvote if it helps ⬆️
---
## Connect with me on Linkedin [Bijoy Sing]
---
###### *Solution in C++, Python, Java, and JavaScript*
```cpp []
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& vals, int k) {
vector<vector<int>> graph(n);
vector<int> degree(n);
if (n < 2) return 1;
for (auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
degree[edge[0]]++;
degree[edge[1]]++;
}
vector<long long> nodeVal(vals.begin(), vals.end());
queue<int> leafQ;
for (int i = 0; i < n; i++)
if (degree[i] == 1) leafQ.push(i);
int compCnt = 0;
while (!leafQ.empty()) {
int curr = leafQ.front();
leafQ.pop();
degree[curr]--;
long long carry = 0;
if (nodeVal[curr] % k == 0) compCnt++;
else carry = nodeVal[curr];
for (int nbr : graph[curr]) {
if (degree[nbr] == 0) continue;
degree[nbr]--;
nodeVal[nbr] += carry;
if (degree[nbr] == 1) leafQ.push(nbr);
}
}
return compCnt;
}
};
```
```python []
class Solution:
def maxKDivisibleComponents(self, n, edges, vals, k):
from collections import deque, defaultdict
if n < 2:
return 1
graph = defaultdict(list)
degree = [0] * n
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
degree[a] += 1
degree[b] += 1
node_vals = vals[:]
leaf_q = deque([i for i in range(n) if degree[i] == 1])
comp_cnt = 0
while leaf_q:
curr = leaf_q.popleft()
degree[curr] -= 1
carry = 0
if node_vals[curr] % k == 0:
comp_cnt += 1
else:
carry = node_vals[curr]
for nbr in graph[curr]:
if degree[nbr] == 0:
continue
degree[nbr] -= 1
node_vals[nbr] += carry
if degree[nbr] == 1:
leaf_q.append(nbr)
return comp_cnt
```
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] vals, int k) {
if (n < 2) return 1;
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
int[] degree = new int[n];
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
degree[edge[0]]++;
degree[edge[1]]++;
}
long[] nodeVals = new long[n];
for (int i = 0; i < n; i++) nodeVals[i] = vals[i];
Queue<Integer> leafQ = new LinkedList<>();
for (int i = 0; i < n; i++) if (degree[i] == 1) leafQ.add(i);
int compCnt = 0;
while (!leafQ.isEmpty()) {
int curr = leafQ.poll();
degree[curr]--;
long carry = 0;
if (nodeVals[curr] % k == 0) compCnt++;
else carry = nodeVals[curr];
for (int nbr : graph.get(curr)) {
if (degree[nbr] == 0) continue;
degree[nbr]--;
nodeVals[nbr] += carry;
if (degree[nbr] == 1) leafQ.add(nbr);
}
}
return compCnt;
}
}
```
```javascript []
class Solution {
maxKDivisibleComponents(n, edges, vals, k) {
if (n < 2) return 1;
const graph = Array.from({ length: n }, () => []);
const degree = Array(n).fill(0);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
degree[a]++;
degree[b]++;
}
const nodeVals = [...vals];
const leafQ = [];
for (let i = 0; i < n; i++) if (degree[i] === 1) leafQ.push(i);
let compCnt = 0;
while (leafQ.length > 0) {
const curr = leafQ.shift();
degree[curr]--;
let carry = 0;
if (nodeVals[curr] % k === 0) compCnt++;
else carry = nodeVals[curr];
for (const nbr of graph[curr]) {
if (degree[nbr] === 0) continue;
degree[nbr]--;
nodeVals[nbr] += carry;
if (degree[nbr] === 1) leafQ.push(nbr);
}
}
return compCnt;
}
}
```
# Intuition
The problem can be approached by considering the graph as a tree and processing it using leaf nodes. The goal is to maximize the number of connected components where the sum of values is divisible by \(k\).
# Approach
1. **Graph Construction:** Represent the graph as an adjacency list and track the degree of each node.
2. **Leaf Node Processing:** Start with all leaf nodes (degree = 1). Use a queue to process nodes level by level.
3. **Value Propagation:** For each leaf node, if its value is divisible by \(k\), increment the result counter. Otherwise, propagate the remainder value to its parent.
4. **Repeat:** Continue this process until all nodes are processed.
5. **Result:** The number of divisible components is stored in the result counter.
# Complexity
- **Time Complexity:**
The algorithm processes each node and edge once, resulting in \(O(n + e)\), where \(n\) is the number of nodes and \(e\) is the number of edges.
- **Space Complexity:**
The space used for the adjacency list and other auxiliary data structures is \(O(n + e)\).
### *If you have any questions or need further clarification, feel free to drop a comment! 😊* | 22 | 1 | ['Topological Sort', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 9 |
maximum-number-of-k-divisible-components | Simple dfs ! | simple-dfs-by-yadivyanshu-sctr | \n\n# Code\n\nclass Solution {\npublic:\n int count = 0, k;\n \n int dfs(int i, vector<bool>& vis, vector<int> adj[], vector<int>& values) {\n v | yadivyanshu | NORMAL | 2023-09-30T17:22:54.272200+00:00 | 2023-09-30T17:22:54.272218+00:00 | 692 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int count = 0, k;\n \n int dfs(int i, vector<bool>& vis, vector<int> adj[], vector<int>& values) {\n vis[i] = true;\n int sum = 0;\n for(auto &j : adj[i]) {\n if(vis[j] == true)continue;\n sum += dfs(j, vis, adj, values);\n }\n sum += values[i];\n if(sum % k == 0)count++, sum = 0;\n return sum;\n }\n \n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n vector<int> adj[n];\n for(auto it : edges) {\n int u = it[0], v = it[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n this->k = k;\n vector<bool> vis(n, false);\n dfs(0, vis, adj, values);\n\n return count;\n }\n};\n``` | 14 | 1 | ['Depth-First Search', 'C++'] | 4 |
maximum-number-of-k-divisible-components | PostOrder Traversal || C++ || Easy to understand | postorder-traversal-c-easy-to-understand-d4en | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | baibhavkr143 | NORMAL | 2023-09-30T16:30:47.618087+00:00 | 2023-09-30T16:31:51.318268+00:00 | 940 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int ans=0;\n vector<vector<int>>adj;\n long long int post(int node,int par,int k,vector<int>&val)\n {\n long long int sum=0;\n for(auto it:adj[node])\n {\n if(it==par)continue;\n sum+=post(it,node,k,val);\n }\n sum+=val[node];\n if(sum%k==0)ans++;\n \n return sum%k;\n }\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n adj.resize(n);\n for(auto it:edges)\n {\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n post(0,-1,k,values);\n return ans;\n }\n};\n``` | 12 | 0 | ['C++'] | 3 |
maximum-number-of-k-divisible-components | 2872. Maximum Number of K-Divisible Com..., Time complexity: O(N*M), Space complexity: O(N*M) | 2872-maximum-number-of-k-divisible-com-t-ansb | IntuitionApproachComplexity
Time complexity: O(N*M)
Space complexity: O(N*M)
Code | richardmantikwang | NORMAL | 2024-12-21T02:07:10.644277+00:00 | 2024-12-21T02:10:48.097925+00:00 | 153 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(N*M)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N*M)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
node_to_adjacent_nodes_map = defaultdict(list)
for u, v in edges:
node_to_adjacent_nodes_map[u].append(v)
node_to_adjacent_nodes_map[v].append(u)
ret_val = 0
def dfs (curr_node, parent):
nonlocal node_to_adjacent_nodes_map
nonlocal ret_val
running_sum = values[curr_node]
for adj_node in node_to_adjacent_nodes_map[curr_node]:
if (adj_node != parent):
running_sum += dfs(adj_node, curr_node)
if (running_sum % k == 0):
ret_val += 1
running_sum = 0
return running_sum
running_sum = dfs(0, -1)
if (running_sum > 0):
ret_val += 1
return ret_val
``` | 11 | 0 | ['Python3'] | 0 |
maximum-number-of-k-divisible-components | Dfs Sum Finding 98% Beats | dfs-sum-finding-98-beats-by-sumeet_sharm-fr5f | 🧠 IntuitionThe problem is based on breaking a tree into components such that the sum of node values in each component is divisible by ( k ). The main observatio | Sumeet_Sharma-1 | NORMAL | 2024-12-21T01:28:50.199812+00:00 | 2024-12-21T01:28:50.199812+00:00 | 1,891 | false | # 🧠 Intuition
The problem is based on breaking a tree into components such that the sum of node values in each component is divisible by \( k \). The main observation is that during a tree traversal, if the cumulative sum of a subtree is divisible by \( k \), we can "cut" the subtree into a separate component. The reset of the sum at this point ensures the divisibility condition doesn't propagate incorrectly to parent nodes.
# 📝 Approach (Step-by-Step)
### 1. Graph Representation
- The tree is represented using an adjacency list. This allows efficient traversal and space-saving representation for a sparse graph like a tree.
### 2. Depth-First Search (DFS)
- Start DFS from the root node (typically node 0) with no parent (`-1`).
- For each node, recursively compute the cumulative sum of values in its subtree, including itself.
### 3. Divisibility Check
- If the cumulative sum of a subtree (rooted at the current node) is divisible by \( k \), the subtree can be "cut" to form a component:
- Increment the count of components (`ans`).
- Reset the sum of the current subtree to \( 0 \) to signify that it no longer contributes to its parent's sum.
### 4. Parent-Child Relationship
- To avoid revisiting nodes, skip the parent node in the DFS recursion.
- This ensures that the DFS strictly moves downward from the root.
### 5. Aggregation of Results
- After the entire DFS traversal, the final count of components (`ans`) represents the maximum number of \( k \)-divisible components.
### 6. Edge Cases
- If all values are \( 0 \), each node can independently form a component.
- If \( k = 1 \), every node's value is divisible by \( k \), so each node becomes a separate component.
- If no subtree sums (including the root) are divisible by \( k \), the entire tree forms one component.
# ⏳ Complexity Analysis
### Time Complexity
- **Tree Traversal**: \( O(n) \), where \( n \) is the number of nodes. Each node and edge is visited exactly once in the DFS.
- **Cumulative Sum Calculation**: Performed during DFS, also \( O(n) \).
Thus, the total time complexity is **\( O(n) \)**.
### Space Complexity
- **Adjacency List**: \( O(n + m) \), where \( n \) is the number of nodes and \( m \) is the number of edges (for a tree, \( m = n - 1 \)).
- **Recursion Stack**: \( O(h) \), where \( h \) is the height of the tree. In the worst case (skewed tree), \( h = n \).
- **Auxiliary Arrays**: \( O(n) \) for storing `values` and `sum`.
Thus, the total space complexity is **\( O(n) \)**.
# 🌟 Detailed Example
### Input
plaintext
n = 7
edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [2, 6]]
values = [3, 6, 9, 1, 2, 1, 4]
k = 3
### Code
```cpp []
class Solution {
int k, ans;
vector<vector<int>> adj;
vector<int> values;
vector<long long> sum;
void dfs(int u, int p) {
sum[u] = values[u];
for (int v : adj[u]) {
if (v == p)
continue;
dfs(v, u);
sum[u] += sum[v];
}
if (sum[u] % k == 0) {
ans++;
sum[u] = 0;
}
}
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges,
vector<int>& values, int k) {
adj.resize(n);
sum.resize(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
this->values = values;
this->k = k;
ans = 0;
dfs(0, -1);
return ans;
}
};
```
```Python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
from collections import defaultdict
def dfs(u, p):
nonlocal ans
subtree_sum = values[u]
for v in adj[u]:
if v != p:
subtree_sum += dfs(v, u)
if subtree_sum % k == 0:
ans += 1
return 0
return subtree_sum
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
ans = 0
dfs(0, -1)
return ans
```
```C []
int maxKDivisibleComponents(int n, int** edges, int edgesSize, int* edgesColSize, int* values, int valuesSize, int k) {
long long* sum = (long long*)calloc(n, sizeof(long long));
int** adj = (int**)malloc(n * sizeof(int*));
int* adjSize = (int*)calloc(n, sizeof(int));
for (int i = 0; i < n; i++) {
adj[i] = (int*)malloc(n * sizeof(int));
}
for (int i = 0; i < edgesSize; i++) {
adj[edges[i][0]][adjSize[edges[i][0]]++] = edges[i][1];
adj[edges[i][1]][adjSize[edges[i][1]]++] = edges[i][0];
}
int ans = 0;
void dfs(int u, int p) {
sum[u] = values[u];
for (int i = 0; i < adjSize[u]; i++) {
int v = adj[u][i];
if (v != p) {
dfs(v, u);
sum[u] += sum[v];
}
}
if (sum[u] % k == 0) {
ans++;
sum[u] = 0;
}
}
dfs(0, -1);
for (int i = 0; i < n; i++) {
free(adj[i]);
}
free(adj);
free(adjSize);
free(sum);
return ans;
}
```
```Java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
int[] sum = new int[n];
List<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
for (int[] edge : edges) {
adj[edge[0]].add(edge[1]);
adj[edge[1]].add(edge[0]);
}
int[] ans = {0};
dfs(0, -1, adj, values, sum, k, ans);
return ans[0];
}
private void dfs(int u, int p, List<Integer>[] adj, int[] values, int[] sum, int k, int[] ans) {
sum[u] = values[u];
for (int v : adj[u]) {
if (v == p) continue;
dfs(v, u, adj, values, sum, k, ans);
sum[u] += sum[v];
}
if (sum[u] % k == 0) {
ans[0]++;
sum[u] = 0;
}
}
}
```
```JavaScript []
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} values
* @param {number} k
* @return {number}
*/
var maxKDivisibleComponents = function(n, edges, values, k) {
const sum = new Array(n).fill(0);
const adj = Array.from({ length: n }, () => []);
edges.forEach(([u, v]) => {
adj[u].push(v);
adj[v].push(u);
});
let ans = 0;
const dfs = (u, p) => {
sum[u] = values[u];
for (const v of adj[u]) {
if (v === p) continue;
dfs(v, u);
sum[u] += sum[v];
}
if (sum[u] % k === 0) {
ans++;
sum[u] = 0;
}
};
dfs(0, -1);
return ans;
};
```
```Ruby []
# @param {Integer} n
# @param {Integer[][]} edges
# @param {Integer[]} values
# @param {Integer} k
# @return {Integer}
def max_k_divisible_components(n, edges, values, k)
adj = Array.new(n) { [] }
edges.each do |u, v|
adj[u] << v
adj[v] << u
end
sum = Array.new(n, 0)
ans = 0
dfs = lambda do |u, p|
sum[u] = values[u]
adj[u].each do |v|
next if v == p
dfs.call(v, u)
sum[u] += sum[v]
end
if sum[u] % k == 0
ans += 1
sum[u] = 0
end
end
dfs.call(0, -1)
ans
end
``` | 10 | 0 | ['C++'] | 0 |
maximum-number-of-k-divisible-components | Python | Depth-First Search (DFS) | python-depth-first-search-dfs-by-khosiya-6zz2 | see the Successfully Accepted SubmissionCodeAlgorithm Overview
Represent the tree using an adjacency list.
Use DFS to traverse the tree and calculate the sum of | Khosiyat | NORMAL | 2024-12-21T00:04:21.879645+00:00 | 2024-12-21T00:04:21.879645+00:00 | 1,797 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484125649/?envType=daily-question&envId=2024-12-21)
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
# Build the adjacency list for the tree
tree = defaultdict(list)
for a, b in edges:
tree[a].append(b)
tree[b].append(a)
# Initialize variables
visited = set()
self.components = 0 # Track the number of valid components
def dfs(node):
# Mark the node as visited
visited.add(node)
# Start the subtree sum with the node's value
subtree_sum = values[node]
for neighbor in tree[node]:
if neighbor not in visited:
# Recursively calculate the subtree sum
child_sum = dfs(neighbor)
# If the child's sum is divisible by k, it's a valid component
if child_sum % k == 0:
self.components += 1
else:
subtree_sum += child_sum
return subtree_sum
# Perform DFS from an arbitrary root (node 0)
total_sum = dfs(0)
# If the entire tree's sum is divisible by k, increment components
if total_sum % k == 0:
self.components += 1
return self.components
```
# Algorithm Overview
1. Represent the tree using an adjacency list.
2. Use DFS to traverse the tree and calculate the sum of values for each subtree.
3. Check divisibility conditions and determine if an edge can be removed.
# Implementation Details
- Use a visited set to avoid revisiting nodes during DFS.
- Track subtree sums and their divisibility by \( k \).
- Count the valid splits based on the divisibility conditions.
# Explanation of the Code
## Adjacency List Construction
We build a tree representation using an adjacency list for easy traversal.
## DFS Functionality
- Traverse each node, summing up the values of its subtree.
- If a subtree's total value is divisible by \( k \), it forms a valid component. Increment the component counter and do not propagate the sum upwards.
- Otherwise, propagate the sum upwards to the parent.
## Counting Components
After traversing the tree, check if the total sum of the entire tree is divisible by \( k \). If so, it forms an additional component.
## Edge Case
The problem guarantees that the sum of all values is divisible by \( k \), so there is always at least one valid component.
# Complexity Analysis
- **Time Complexity:** \( O(n) \), where \( n \) is the number of nodes, since we visit each node once.
- **Space Complexity:** \( O(n) \), for the adjacency list and recursion stack.
 | 10 | 0 | ['Python3'] | 1 |
maximum-number-of-k-divisible-components | Easy to understand DFS✅✅ || O(n) Solution | easy-to-understand-dfs-on-solution-by-ar-kcbl | Approach
First, calculate the subtree size(value of subtree) for every node in the tree using the getSubtree function. This function recursively computes the su | arunk_leetcode | NORMAL | 2024-12-21T05:26:10.737874+00:00 | 2024-12-21T05:29:48.529512+00:00 | 3,047 | false | # Approach
<!-- Describe your approach to solving the problem. -->
1. First, calculate the `subtree size(value of subtree)` for every node in the tree using the getSubtree function. This function recursively computes the sum of the values in the subtree rooted at each node.
2. The while doing `dfs` just check if that particular edge can be broken or not.
3. If the edge can be broken then update the `subtree size` of the parent.
4. If the edge cannot be broken then just pass the `subtree size` of parent to the child so that child bears the `value of the component`.
5. Finally the answer is `cnt+1` which is the number of components.
# Complexity
- Time complexity: $$O(N+E)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(N+E)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
#define ll long long
void getSubtree(int node, vector<vector<int>>& adj, int par, vector<ll>& subtree){
if(adj[node].size() == 1 && adj[node][0] == par){
return;
}
for(auto it: adj[node]){
if(it!=par){
getSubtree(it, adj, node, subtree);
subtree[node]+=subtree[it];
}
}
}
int cnt = 0;
void dfs(int node, vector<vector<int>>& adj, int par, vector<ll>& subtree, int k){
if(adj[node].size() == 1 && adj[node][0] == par){
return;
}
for(auto it: adj[node]){
if(it!=par){
ll parSubtree = subtree[node] - subtree[it];
ll childSubtree = subtree[it];
if(parSubtree%k == 0 && childSubtree%k == 0){
cnt++;
subtree[node]-=subtree[it];
}
else subtree[it] = subtree[node];
dfs(it, adj, node, subtree, k);
}
}
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adj(n+1);
for(auto it: edges){
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
vector<ll> subtree;
for(auto it: values){
subtree.push_back(it*1LL);
}
getSubtree(0, adj, -1, subtree);
for(auto it: subtree) cout<< it <<" ";
dfs(0, adj, -1, subtree, k);
return cnt+1;
}
};
```
``` Java []
import java.util.*;
class Solution {
private long cnt = 0;
private void getSubtree(int node, List<List<Integer>> adj, int parent, long[] subtree) {
if (adj.get(node).size() == 1 && adj.get(node).get(0) == parent) return;
for (int neighbor : adj.get(node)) {
if (neighbor != parent) {
getSubtree(neighbor, adj, node, subtree);
subtree[node] += subtree[neighbor];
}
}
}
private void dfs(int node, List<List<Integer>> adj, int parent, long[] subtree, int k) {
if (adj.get(node).size() == 1 && adj.get(node).get(0) == parent) return;
for (int neighbor : adj.get(node)) {
if (neighbor != parent) {
long parSubtree = subtree[node] - subtree[neighbor];
long childSubtree = subtree[neighbor];
if (parSubtree % k == 0 && childSubtree % k == 0) {
cnt++;
subtree[node] -= subtree[neighbor];
} else {
subtree[neighbor] = subtree[node];
}
dfs(neighbor, adj, node, subtree, k);
}
}
}
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
long[] subtree = new long[n];
for (int i = 0; i < n; i++) subtree[i] = values[i];
getSubtree(0, adj, -1, subtree);
dfs(0, adj, -1, subtree, k);
return (int) (cnt + 1);
}
}
```
``` Python []
class Solution:
def __init__(self):
self.cnt = 0
def getSubtree(self, node, adj, parent, subtree):
if len(adj[node]) == 1 and adj[node][0] == parent:
return
for neighbor in adj[node]:
if neighbor != parent:
self.getSubtree(neighbor, adj, node, subtree)
subtree[node] += subtree[neighbor]
def dfs(self, node, adj, parent, subtree, k):
if len(adj[node]) == 1 and adj[node][0] == parent:
return
for neighbor in adj[node]:
if neighbor != parent:
parSubtree = subtree[node] - subtree[neighbor]
childSubtree = subtree[neighbor]
if parSubtree % k == 0 and childSubtree % k == 0:
self.cnt += 1
subtree[node] -= subtree[neighbor]
else:
subtree[neighbor] = subtree[node]
self.dfs(neighbor, adj, node, subtree, k)
def maxKDivisibleComponents(self, n, edges, values, k):
adj = [[] for _ in range(n + 1)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
subtree = [val for val in values]
self.getSubtree(0, adj, -1, subtree)
self.dfs(0, adj, -1, subtree, k)
return self.cnt + 1
``` | 8 | 0 | ['Tree', 'Depth-First Search', 'Python', 'C++', 'Java', 'Python3'] | 3 |
maximum-number-of-k-divisible-components | Easy Video Solution(C++,JAVA,Python)🔥 || DFS + Indegree 🔥 | easy-video-solutioncjavapython-dfs-indeg-8k5o | Intuition\n Describe your first thoughts on how to solve this problem. \nStart thinking from leaf Nodes\n\n# Detailed and easy Video Solution\n\nhttps://youtu.b | ayushnemmaniwar12 | NORMAL | 2023-09-30T19:06:42.201061+00:00 | 2023-09-30T19:06:42.201088+00:00 | 674 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart thinking from leaf Nodes\n\n# ***Detailed and easy Video Solution***\n\nhttps://youtu.be/JvgvAhKPBcI\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe problem is to determine the maximum number of connected components in a graph. Each component must satisfy a specific condition: the sum of values associated with its nodes should be divisible by a given integer \'k\'. The input includes the graph represented by its nodes, edges, and values for each node. The code employs a breadth-first search (BFS) approach to traverse the graph, identifying connected components that meet the condition. It keeps track of in-degrees, distributes values among nodes, and counts the components satisfying the condition. The algorithm operates in O(n) time complexity, where \'n\' is the number of nodes, and consumes O(n) space due to adjacency list and queue storage.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n The time complexity of the given code is O(n), in the worst case.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity of the code is O(n + k)\n\n```C++ []\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& v, vector<int>& values, int k) {\n vector<int>adj[n+1];\n vector<int>in(n+1,0);\n for(int i=0;i<n-1;i++)\n {\n adj[v[i][0]].push_back(v[i][1]);\n adj[v[i][1]].push_back(v[i][0]);\n in[v[i][0]]++;\n in[v[i][1]]++;\n }\n queue<int>q;\n for(int i=0;i<n;i++)\n {\n if(in[i]==1 || in[i]==0)\n q.push(i);\n }\n int c=0;\n while(!q.empty())\n {\n queue<int>q1;\n while(!q.empty())\n {\n int f=q.front();\n q.pop();\n in[f]=0;\n if(values[f]%k==0)\n {\n c++;\n values[f]=0;\n }\n for(auto i:adj[f])\n {\n if(in[i]!=0)\n {\n in[i]--;\n values[i]+=values[f];\n if(in[i]==1)\n q1.push(i);\n }\n }\n }\n q=q1;\n }\n return c;\n }\n};\n```\n```python []\nfrom collections import defaultdict, deque\n\nclass Solution:\n def maxKDivisibleComponents(self, n, v, values, k):\n adj = defaultdict(list)\n in_degree = [0] * (n + 1)\n\n for i in range(n - 1):\n u, w = v[i][0], v[i][1]\n adj[u].append(w)\n adj[w].append(u)\n in_degree[u] += 1\n in_degree[w] += 1\n\n q = deque()\n for i in range(n):\n if in_degree[i] == 1 or in_degree[i] == 0:\n q.append(i)\n\n c = 0\n while q:\n q1 = deque()\n while q:\n f = q.popleft()\n in_degree[f] = 0\n if values[f] % k == 0:\n c += 1\n values[f] = 0\n for i in adj[f]:\n if in_degree[i] != 0:\n in_degree[i] -= 1\n values[i] += values[f]\n if in_degree[i] == 1:\n q1.append(i)\n q = q1\n\n return c\n\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n public int maxKDivisibleComponents(int n, int[][] v, int[] values, int k) {\n List<Integer>[] adj = new ArrayList[n + 1];\n int[] in = new int[n + 1];\n for (int i = 0; i < n - 1; i++) {\n int u = v[i][0];\n int w = v[i][1];\n if (adj[u] == null) {\n adj[u] = new ArrayList<>();\n }\n if (adj[w] == null) {\n adj[w] = new ArrayList<>();\n }\n adj[u].add(w);\n adj[w].add(u);\n in[u]++;\n in[w]++;\n }\n Queue<Integer> q = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (in[i] == 1 || in[i] == 0) {\n q.offer(i);\n }\n }\n int c = 0;\n while (!q.isEmpty()) {\n Queue<Integer> q1 = new LinkedList<>();\n while (!q.isEmpty()) {\n int f = q.poll();\n in[f] = 0;\n if (values[f] % k == 0) {\n c++;\n values[f] = 0;\n }\n for (int i : adj[f]) {\n if (in[i] != 0) {\n in[i]--;\n values[i] += values[f];\n if (in[i] == 1) {\n q1.offer(i);\n }\n }\n }\n }\n q = q1;\n }\n return c;\n }\n}\n\n```\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n*It Motivates me to record more videos*\n\n***Thank you*** \uD83D\uDE00 | 8 | 0 | ['Breadth-First Search', 'Graph', 'C++', 'Java', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | Simple ✅ || Easy to Understand ✅ || beat 100% ✅ | simple-easy-to-understand-beat-100-by-th-0xgc | Intuition:\nWe are given a tree with nodes having integer values. We need to find the number of subtrees in the tree such that the sum of values in each subtree | thesaurabhmhaske | NORMAL | 2023-09-30T18:35:25.420159+00:00 | 2023-09-30T18:35:25.420179+00:00 | 320 | false | # Intuition:\nWe are given a tree with nodes having integer values. We need to find the number of subtrees in the tree such that the sum of values in each subtree is divisible by \'k\'. We can solve this problem using Depth-First Search (DFS) to traverse the tree.\n\n# Approach:\n\n- Initialize a count \'cnt\' to keep track of the number of k-divisible components.\n- Build an adjacency list representation of the tree.\nStart DFS from the root node (node 0) and traverse the tree.\n- In the DFS function:\na. Initialize \'sum\' with the value of the current node.\nb. Traverse through the adjacent nodes and recursively calculate the sum of values for the subtree rooted at each adjacent node.\nc. Check if \'sum\' is divisible by \'k\'. If it is, increment \'cnt\' to count the k-divisible component and return 0 to indicate that this subtree is k-divisible. Otherwise, return \'sum\' as the sum of values for this subtree.\nFinally, return \'cnt\' as the count of k-divisible components in the tree.\nComplexity:\n\n# Time complexity:\n- The DFS algorithm visits each node once, and for each node, it performs constant-time operations.\nTherefore, the time complexity is O(n), where n is the number of nodes in the tree.\n# Space complexity:\n- The space complexity is O(n) due to the space used for the adjacency list and the recursive stack in the DFS.\nThis code efficiently finds the count of k-divisible components in a tree.#\n\n# Code\n```\nclass Solution {\npublic:\n long long dfs(int &ans, vector<int>&values, int node, int prevNode, unordered_map<int,list<int>>&adj, int &k){\n \n long long sum=values[node];\n for(auto it:adj[node]){\n if(it==prevNode) continue;\n sum += dfs(ans,values,it,node,adj,k);\n }\n if(sum%k==0){\n ans++;\n return 0;\n }\n else return (long long)sum;\n }\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n unordered_map<int,list<int>>adj(n);\n for(int i=0;i<edges.size();i++){\n int u=edges[i][0];\n int v = edges[i][1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n int cnt=0;\n dfs(cnt,values,0,-1,adj,k);\n return cnt;\n }\n};\n``` | 8 | 0 | ['Tree', 'Depth-First Search', 'Graph', 'C++'] | 2 |
maximum-number-of-k-divisible-components | DFS for Tree Traversal😎|| Written in JavaScript | dfs-for-tree-traversal-written-in-javasc-f90b | Complexity
Time complexity: O(n)
Space complexity: O(n)
Code | yenhuynh02 | NORMAL | 2024-12-21T05:17:36.325004+00:00 | 2024-12-21T05:17:36.325004+00:00 | 420 | false | # Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```javascript []
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} values
* @param {number} k
* @return {number}
*/
var maxKDivisibleComponents = function(n, edges, values, k) {
// Step 1: Build the adjacency list representation of the tree
const tree = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
tree[a].push(b);
tree[b].push(a);
}
// Step 2: Perform DFS to calculate subtree sums
const subtreeSum = Array(n).fill(0);
const visited = Array(n).fill(false);
function dfs(node) {
visited[node] = true;
let sum = values[node];
for (const neighbor of tree[node]) {
if (!visited[neighbor]) {
sum += dfs(neighbor);
}
}
subtreeSum[node] = sum;
return sum;
}
// Perform DFS from the root (node 0)
dfs(0);
// Step 3: Check for valid splits
let maxComponents = 1; // At least one component (the whole tree)
function dfsCount(node) {
visited[node] = true;
let componentCount = 0;
for (const neighbor of tree[node]) {
if (!visited[neighbor]) {
if (subtreeSum[neighbor] % k === 0) {
componentCount++; // Split here
}
componentCount += dfsCount(neighbor);
}
}
return componentCount;
}
// Reset visited array and count components
visited.fill(false);
maxComponents += dfsCount(0);
return maxComponents;
};
``` | 7 | 0 | ['Tree', 'Depth-First Search', 'JavaScript'] | 0 |
maximum-number-of-k-divisible-components | Easy Java Solution using DFS in O(n) | easy-java-solution-using-dfs-in-on-by-wh-8abf | Approach\n Describe your approach to solving the problem. \nThe code aims to find the number of components in a graph such that the sum of values in each compon | whopiyushanand | NORMAL | 2023-10-03T08:49:12.818985+00:00 | 2023-10-03T08:49:12.819007+00:00 | 180 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe code aims to find the number of components in a graph such that the sum of values in each component is divisible by k. It uses a Depth-First Search (DFS) approach to traverse the graph.\n\n- Create an adjacency list to represent the graph where each node has a list of its neighboring nodes.\n- Initialize a variable ans to count the number of components that meet the condition.\n- Start a DFS traversal from node 0 (or any starting node). For each component encountered during the traversal:\n - Compute the sum of values of nodes in the component.\n - If the sum is divisible by k, increment ans.\n- Return the ans as the result.\n\n# Complexity\n- Time complexity:O(V + E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(V)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n adj.add(new ArrayList<>());\n }\n for (int[] edge : edges) {\n adj.get(edge[0]).add(edge[1]);\n adj.get(edge[1]).add(edge[0]);\n }\n\n int[] ans = new int[1]; \n dfs(0, -1, ans, adj, values, k); // 0=node, -1=parent\n return ans[0]; \n }\n\n int dfs(int node, int parent, int[] ans, ArrayList<ArrayList<Integer>> adj, int[] values, int k) {\n int sum = values[node];\n\n for (Integer neighbour : adj.get(node)) {\n if (neighbour != parent) {\n sum += dfs(neighbour, node, ans, adj, values, k);\n }\n }\n if (sum % k == 0) {\n ans[0]++; // Update ans using the array\n return 0;\n }\n return sum;\n }\n}\n\n``` | 7 | 0 | ['Tree', 'Depth-First Search', 'Java'] | 3 |
maximum-number-of-k-divisible-components | ✅100% Faster | DFS | Easy Intuitive approach | Java | C++ | Python | Detailed Video Explanation 🔥 | 100-faster-dfs-easy-intuitive-approach-j-9d0t | IntuitionThe problem can be thought of as dividing the graph into subtrees where the sum of the node values is divisible by k. By using Depth First Search (DFS) | sahilpcs | NORMAL | 2024-12-21T12:32:33.184043+00:00 | 2024-12-21T12:32:33.184043+00:00 | 766 | false | # Intuition
The problem can be thought of as dividing the graph into subtrees where the sum of the node values is divisible by `k`. By using Depth First Search (DFS), we can traverse the graph and calculate the sum of values in each subtree while keeping track of these divisible components.
# Approach
1. **Graph Representation**:
- Use an adjacency list to represent the graph from the given edges.
2. **DFS Traversal**:
- Start a DFS from an arbitrary root (node `0`) while keeping track of the parent node to prevent revisiting edges.
- At each node, calculate the sum of the values in the current subtree, including the value of the node itself.
- If the sum of a subtree modulo `k` equals `0`, it signifies a `k`-divisible component. Increment the count for such cases.
3. **Recursive Processing**:
- Return the sum of the current subtree to its parent to continue the DFS.
4. **Final Count**:
- The global counter keeps track of all the `k`-divisible components found during the traversal.
# Complexity
- Time complexity:
- $$O(n)$$: Each node and edge is visited exactly once during the DFS traversal.
- Space complexity:
- $$O(n)$$: The adjacency list and recursion stack both require space proportional to the number of nodes in the graph.
# Code
```java []
class Solution {
int count; // Global variable to keep track of the number of k-divisible components
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
// Prepare adjacency list to represent the graph
ArrayList[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
count = 0; // Initialize the count of k-divisible components to 0
// Build the adjacency list from the edges
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adj[u].add(v); // Add v to u's adjacency list
adj[v].add(u); // Add u to v's adjacency list (since the graph is undirected)
}
// Start DFS traversal from node 0 with -1 as the parent (no parent for the root)
sol(0, -1, adj, values, k);
// Return the total number of k-divisible components found
return count;
}
// Helper method for DFS traversal
private int sol(int curr, int prev, ArrayList<Integer>[] adj, int[] values, int k) {
int sum = 0; // Initialize the sum of values for the current subtree
// Iterate over all adjacent nodes of the current node
for (int v : adj[curr]) {
if (v == prev) continue; // Skip the parent node to avoid revisiting it
sum += sol(v, curr, adj, values, k); // Recursive call to process the subtree rooted at v
}
sum += values[curr]; // Add the value of the current node to the sum
sum = sum % k; // Reduce the sum modulo k
// If the sum modulo k is 0, we found a k-divisible component
if (sum == 0) {
count++; // Increment the count of k-divisible components
}
// Return the sum of the subtree to the parent node
return sum;
}
}
```
```c++ []
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
int count; // Global variable to keep track of k-divisible components
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
// Prepare adjacency list to represent the graph
vector<vector<int>> adj(n);
for (auto& edge : edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
count = 0; // Initialize count to 0
dfs(0, -1, adj, values, k); // Start DFS from node 0
return count;
}
private:
int dfs(int curr, int prev, vector<vector<int>>& adj, vector<int>& values, int k) {
int sum = 0; // Initialize sum of the current subtree
// Iterate over all adjacent nodes
for (int v : adj[curr]) {
if (v == prev) continue; // Skip the parent node
sum += dfs(v, curr, adj, values, k); // Process the subtree rooted at v
}
sum += values[curr]; // Add current node's value
sum %= k; // Reduce the sum modulo k
if (sum == 0) {
count++; // Increment the count for k-divisible components
}
return sum; // Return the sum of the subtree
}
};
```
```python []
from typing import List
class Solution:
def __init__(self):
self.count = 0 # Global variable to keep track of k-divisible components
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
# Prepare adjacency list to represent the graph
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# Start DFS from node 0 with -1 as parent
self.dfs(0, -1, adj, values, k)
return self.count
def dfs(self, curr: int, prev: int, adj: List[List[int]], values: List[int], k: int) -> int:
sum_ = 0 # Initialize sum of the current subtree
# Iterate over all adjacent nodes
for v in adj[curr]:
if v == prev:
continue # Skip the parent node
sum_ += self.dfs(v, curr, adj, values, k) # Process the subtree rooted at v
sum_ += values[curr] # Add current node's value
sum_ %= k # Reduce the sum modulo k
if sum_ == 0:
self.count += 1 # Increment the count for k-divisible components
return sum_ # Return the sum of the subtree
```
LeetCode 2872 Maximum Number of K Divisible Components | Tree | Hard | Asked in Google
https://youtu.be/xAryABE4AgU
| 6 | 0 | ['Tree', 'Depth-First Search', 'Python', 'C++', 'Java'] | 2 |
maximum-number-of-k-divisible-components | 💢Faster✅💯 Lesser C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 💯 | faster-lesser-cpython3javacpythoncexplai-19r4 | IntuitionApproach
JavaScript Code --> https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484229155
C++ Code --> https://leetcod | Edwards310 | NORMAL | 2024-12-21T05:18:26.267934+00:00 | 2024-12-21T05:18:26.267934+00:00 | 734 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your first thoughts on how to solve this problem. -->
- ***JavaScript Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484229155
- ***C++ Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484184171
- ***Python3 Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484206268
- ***Java Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484193353
- ***C Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484230635
- ***C# Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484224933
- ***Go Code -->*** https://leetcode.com/problems/maximum-number-of-k-divisible-components/submissions/1484229155
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code

``` | 5 | 0 | ['Tree', 'Depth-First Search', 'C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#'] | 0 |
maximum-number-of-k-divisible-components | Easy | DFS | easy-dfs-by-kamlesh012-x6rq | \nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n \n vector<vector<i | kamlesh012 | NORMAL | 2023-10-01T13:56:33.480264+00:00 | 2023-10-01T13:56:33.480291+00:00 | 169 | false | ```\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n \n vector<vector<int>> adjl(n);\n for(auto i:edges){\n adjl[i[0]].push_back(i[1]);\n adjl[i[1]].push_back(i[0]);\n }\n int cnt=0ll;\n\n function<int(int,int)> dfs=[&](int src,int parent){\n int sum=values[src];\n for(auto i:adjl[src]){\n if(i!=parent){\n sum+=dfs(i,src);\n sum%=k;\n }\n }\n if(sum%k==0)cnt++;\n return sum;\n };\n dfs(0,-1);\n return cnt;\n }\n};\n``` | 5 | 0 | ['Depth-First Search'] | 1 |
maximum-number-of-k-divisible-components | Java O(n) visit each subtree (DFS) | java-on-visit-each-subtree-dfs-by-ricola-i8wv | We start from the bottom of the tree.\u2028For each subtree we visit, we compute the sum of all its nodes (excluding the ones already split).\u2028If it\u2019s | ricola | NORMAL | 2023-09-30T16:01:32.424431+00:00 | 2023-10-01T09:43:29.057606+00:00 | 433 | false | We start from the bottom of the tree.\u2028For each subtree we visit, we compute the sum of all its nodes (excluding the ones already split).\u2028If it\u2019s divisible by k, it means that this subtree can be split from its parent.\n\n\nYou could ask : \u201CHow do we know that we should only consider entire subtrees?\u201D\u2028For example, with this tree:\n``` \n A\n / \\\n B C\n```\nYou could ask \u201Cwhat if (sum(A) + sum(B)) % k == 0 ?\u201D. \nThen it means we would leave C alone. And since we visited C before A and it wasn\u2019t split, this means C % k != 0. We cannot leave C as its own component, we have to include it in this component.\n\n```\nclass Solution {\n private int count = 0;\n private int k;\n\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n this.k = k;\n \n // build the tree\n Node[] nodes = new Node[n];\n for (int i = 0; i < n; i++) {\n nodes[i] = new Node(values[i]);\n }\n\n for (int[] edge : edges) {\n Node a = nodes[edge[0]];\n Node b = nodes[edge[1]];\n a.neighbors.add(b);\n b.neighbors.add(a);\n }\n\n // visit the tree from the root\n getSum(nodes[0], null);\n return count;\n\n }\n\n // returns the sum of the subtree rooted at node\n private int getSum(Node node, Node parent){\n int sum = node.value;\n for (Node neighbor : node.neighbors) {\n if(neighbor == parent) continue;\n sum += getSum(neighbor, node);\n }\n\n if(sum %k == 0){\n count++;\n return 0;\n }\n return sum;\n }\n\n\n private static class Node{\n int value;\n List<Node> neighbors = new ArrayList<>();\n\n public Node(int value) {\n this.value = value;\n }\n }\n}\n```\n | 5 | 1 | ['Breadth-First Search', 'Java'] | 3 |
maximum-number-of-k-divisible-components | DFS in python split if sum % k == 0 | dfs-in-python-split-if-sum-k-0-by-dinesh-572k | The sum of all nodes in the tree is always divisible by k.\nThus if a subtree with sum \'s\' is divisible by k then the rest of subtree sum \'temp\' will always | dinesh55 | NORMAL | 2023-09-30T16:01:01.598355+00:00 | 2023-09-30T16:01:54.647913+00:00 | 356 | false | The sum of all nodes in the tree is always divisible by k.\nThus if a subtree with sum \'s\' is divisible by k then the rest of subtree sum \'temp\' will always be divisible by k.\nHence all we have to do is <b>find the subtrees with sum % k == 0 and cut them </b>\n\nTo find the subtrees we will use DFS\n\npython code :\n\n```\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n visited = [False for _ in range(n)]\n self.ans = 0\n graph = [[] for _ in range(n)]\n for u,v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n def dfs(node)->int:\n visited[node] = True\n sums = values[node]\n\t\t\t# iterate over the neighbours\n for nei in graph[node]:\n\t\t\t\t# if neighbour was visited continue\n\t\t\t\tif visited[nei]: continue\n\t\t\t\ttemp = dfs(nei)\n\t\t\t\t# if the neighbour subtree sum is divisible by k then we cut it hence we don\'t add it to sums\n if temp % k == 0:\n self.ans += 1\n else:\n\t\t\t\t# if neighbour subtree sum is not divisible by k then this subtree will have to rely on the parent \n\t\t\t\t# to make sum % k == 0 thus we add it to parent.\n sums += temp\n return sums\n dfs(0)\n\t\t# if we make x cuts there will be x + 1 trees \n return self.ans + 1\n \n```\n\nTime complexity : O(n) | 5 | 0 | ['Depth-First Search', 'Graph', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | Video Explanation (Solving problem step by step from scratch) | video-explanation-solving-problem-step-b-gdqh | Explanation\n\nClick here for the video\n\n# Code\n\ntypedef long long int ll;\nconst int N = 3e4+5;\n\nvector<vector<int>> g(N);\nvector<ll> val(N);\nint resul | codingmohan | NORMAL | 2023-09-30T16:33:08.015630+00:00 | 2023-09-30T16:33:08.015652+00:00 | 108 | false | # Explanation\n\n[Click here for the video](https://youtu.be/PZQLUgYwfJA)\n\n# Code\n```\ntypedef long long int ll;\nconst int N = 3e4+5;\n\nvector<vector<int>> g(N);\nvector<ll> val(N);\nint result;\nint K;\n\nint MaxComponents (int src, int par) {\n ll leftOver = val[src];\n \n for (auto i : g[src]) {\n if (i == par) continue;\n leftOver += MaxComponents(i, src);\n }\n if (leftOver % K == 0) {\n result ++;\n leftOver = 0;\n }\n return leftOver;\n}\n\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n result = 0;\n K = k;\n for (int j = 0; j < n; j ++) {\n g[j].clear();\n val[j] = values[j];\n }\n for (auto e : edges) {\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n \n ll leftOver = MaxComponents(0, -1);\n if (leftOver != 0) result ++;\n \n return result;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
maximum-number-of-k-divisible-components | [Python3/C++/Java/Go] DFS -Detailed Explanation | python3cjavago-dfs-detailed-explanation-4y0s3 | Intuition
Finding the maximum components -> go up from leaves whenever we first meet group that divisible by k -> cut it immediately. Because the total values i | dolong2110 | NORMAL | 2024-12-21T11:58:59.220402+00:00 | 2024-12-21T19:08:13.677218+00:00 | 173 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- Finding the maximum components -> go up from leaves whenever we first meet group that divisible by `k` -> cut it immediately. Because the total values is divisible for `k`, so cut soon is a greedy way to achieve it.
# Approach
<!-- Describe your approach to solving the problem. -->
This code solves the problem of finding the maximum number of components in a tree where each component's value (sum of node values) is divisible by `k`. It uses a Depth First Search (DFS) approach to traverse the tree and calculate the component values.
## 1. Building the Graph:
- `g = collections.defaultdict(set)`: This creates a dictionary-like structure where keys are nodes, and values are sets of their neighboring nodes. This represents the tree structure in an adjacency list format. This allows efficient retrieval of neighbors for each node.
- `for u, v in edges`: This loop iterates through the `edges` list to populate the `g` dictionary. For each edge `[u, v]`, it adds `v` to the neighbor set of `u` and vice versa, effectively constructing the adjacency list representation of the tree.
## 2. DFS Traversal:
- `res = 1`: Initializes a counter for the number of valid components. It starts with 1 because initially, the whole tree is considered as one component.
- `def dfs(node=0) -> int`: This defines a recursive function for DFS traversal.
- It takes the current `node` as input (defaulting to 0, the root of the tree) and returns the total value of the subtree rooted at that node.
- `nonlocal res`: This statement allows the `dfs` function to modify the `res` variable defined in the outer scope.
- `total = values[node]`: Initializes the `total` variable with the value of the current node.
- `for next_node in g[node]`: This loop iterates through the neighbors of the current node.
- `g[next_node].remove(node)`: This line removes the current node (`node`) from the neighbor's (`next_node`) adjacency list. This is important to prevent revisiting the same node and causing infinite recursion in the DFS traversal.
- `next_total = dfs(next_node)`: This recursively calls the `dfs` function for the neighbor (`next_node`) to get the total value of its subtree.
- `if next_total % k == 0`: This condition checks if the total value of the neighbor's subtree (`next_total`) is divisible by `k`. If it is, it means this subtree can be a valid component on its own, so the `res` (component count) is incremented by 1.
- `else`: If the neighbor's subtree value is not divisible by `k`, it cannot be a separate component. In this case, its value (`next_total`) is added to the `total` of the current subtree.
- `return total`: After processing all neighbors, the function returns the `total` value of the subtree rooted at the current node.
## 3. Main Execution:
- `dfs()`: This line initiates the DFS traversal starting from the root node (node 0).
# Complexity
- Time complexity: $$O(N)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(N)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
g = collections.defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
res = 1
def dfs(node: int=0) -> int:
nonlocal res
total = values[node]
for next_node in g[node]:
g[next_node].remove(node)
next_total = dfs(next_node)
if next_total % k == 0: res += 1
else: total += next_total
return total
dfs()
return res
```
```C++ []
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
unordered_map<int, unordered_set<int>> g;
for (auto& edge : edges) {
g[edge[0]].insert(edge[1]);
g[edge[1]].insert(edge[0]);
}
int res = 1;
function<int(int)> dfs = [&](int node) {
int total = values[node];
for (int next_node : g[node]) {
g[next_node].erase(node);
int next_total = dfs(next_node);
if (next_total % k == 0) {
res++;
} else {
total += next_total;
}
}
return total % k;
};
dfs(0);
return res;
}
};
```
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
Map<Integer, Set<Integer>> g = new HashMap<>();
for (int[] edge : edges) {
g.computeIfAbsent(edge[0], key -> new HashSet<>()).add(edge[1]);
g.computeIfAbsent(edge[1], key -> new HashSet<>()).add(edge[0]);
}
int[] res = {1}; // Use an array to modify within lambda
dfs(0, g, values, k, res);
return res[0];
}
private int dfs(int node, Map<Integer, Set<Integer>> g, int[] values, int k, int[] res) {
int total = values[node];
for (int next_node : g.getOrDefault(node, new HashSet<>())) {
g.get(next_node).remove(node);
int next_total = dfs(next_node, g, values, k, res);
if (next_total % k == 0) {
res[0]++;
} else {
total += next_total;
}
}
return total % k;
}
}
```
```go []
func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) int {
g := make(map[int]map[int]bool)
for _, edge := range edges {
u, v := edge[0], edge[1]
if g[u] == nil {
g[u] = make(map[int]bool)
}
if g[v] == nil {
g[v] = make(map[int]bool)
}
g[u][v] = true
g[v][u] = true
}
res := 1
var dfs func(int) int
dfs = func(node int) int {
total := values[node]
for next_node := range g[node] {
delete(g[next_node], node)
next_total := dfs(next_node)
if next_total%k == 0 {
res++
} else {
total += next_total
}
}
return total
}
dfs(0)
return res
}
``` | 3 | 0 | ['Tree', 'Depth-First Search', 'C++', 'Java', 'Go', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | an intuitive? "top down" approach using euler tour and prefix sum | an-intuitive-top-down-approach-using-eul-ebbe | Intuition and ApproachFirstly, we observe that the sum of all nodes in the tree must be nk for some n∈N.Consider a simple case, a tree with root 1 and leaves 2 | ui_beam | NORMAL | 2024-12-21T08:54:46.764742+00:00 | 2024-12-21T08:54:46.764742+00:00 | 83 | false | # Intuition and Approach
Firstly, we observe that the sum of all nodes in the tree must be $$nk$$ for some $$n \in \N $$.
Consider a simple case, a tree with root 1 and leaves 2 and 3, with values 1,2,3 respectively, with $$k = 3$$.
We have two edges we can possibly "cut" and remove from our graph (i.e 1-2 and 1-3). Obviously, we cannot cut the edge 1-2 as this will leave us with the component with $$\{2\}$$ and the component with $$\{1,3\}$$, neither of which are divisble by three. We must then cut the edge 1-3, and this correctly leaves us with the component with $$\{1,2\}$$ and the component with $$\{3\}$$.
Now consider the general case, where we have some vertex $$v$$ with subtrees, $$l$$ and $$r$$. Can we try and extend this intuition we found from the smaller case to the general case?
Why were we able to cut the edge 1-3 and not 1-2?
Cutting the edge 1-2 results in subtrees whose sums are 2 and 4 (not divisble by $$k$$), while cutting the edge 1-3 results in subtrees whose sizes are 3 and 3(divisible by $$k$$).
Now let's briefly take a look back at our initial observation, that the entire tree must sum to $$nk$$. If we choose to remove an edge to a subtree of sum $$mk$$, it **must** follow that our original tree is left with a sum of$$(n-m)k$$.
So now we have this notion of splitting a tree whose sum is divisble by $$k$$ into subtrees who have sums divisible by $$k$$. We can think of this recursively, solving the problems for each subtree like we did with our original tree.
Thus, this problem can be reduced to finding subtree sums, which can be solved with the Euler Tour and Prefix Sum techniques (https://usaco.guide/gold/tree-euler?lang=cpp).
The algorithm is simply as follows:
- For each node in our tree,
- Check if any of its children are roots of subtrees whose sum is divisble by k.
- If so, we have a new component.
I will leave formally proving the optimality of this algoritm as an exercise to you. ♥
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(n)$$
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
# build graph
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
# arrays for euler tour
first = [-1] * n
last = [-1] * n
tour = []
timer = [0]
# euler tour, record entry and exit "time"
def dfs(u: int, parent: int):
first[u] = timer[0]
tour.append(values[u])
timer[0] += 1
for v in adj[u]:
if v != parent:
dfs(v, u)
last[u] = timer[0]
dfs(0, -1)
# prefix sums for subtree queries
prefix_sum = [0] * (len(tour) + 1)
for i in range(len(tour)):
prefix_sum[i + 1] = prefix_sum[i] + tour[i]
result = [1] # we always have at least one tree
# recursively count k-divisible subtrees
def solve(u: int, parent: int):
for v in adj[u]:
if v != parent:
subtree_sum = prefix_sum[last[v]] - prefix_sum[first[v]]
# if subtree sum is divisible by k, count it as a component
result[0] += subtree_sum % k == 0
solve(v, u)
solve(0, -1)
return result[0]
``` | 3 | 0 | ['Tree', 'Depth-First Search', 'Prefix Sum', 'Eulerian Circuit', 'Python3'] | 2 |
maximum-number-of-k-divisible-components | DFS || C++ solution | dfs-c-solution-by-ashishcoder2002-yove | IntuitionApproachComplexity
Time complexity:
O(N)
Space complexity:
Code | ashishcoder2002 | NORMAL | 2024-12-21T08:38:29.521640+00:00 | 2024-12-21T08:38:29.521640+00:00 | 198 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(N)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int ans = 0;
long dfs(int i, vector<vector<int>>& adj, vector<int>& vis,vector<int>& val, int k) {
vis[i] = 1;
long sum = 0;
for(auto node : adj[i]) {
if(!vis[node]) {
sum += dfs(node, adj, vis, val, k);
}
}
sum += val[i];
if(sum%k == 0) {
ans++;
return 0;
}
return sum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adj(n);
vector<int> vis(n,0);
for(auto i : edges) {
adj[i[0]].push_back(i[1]);
adj[i[1]].push_back(i[0]);
}
dfs(0, adj, vis, values, k);
return ans;
}
};
``` | 3 | 0 | ['Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | 💡 Easy simple || DFS || Prefix Sum 🎯 | easy-simple-dfs-prefix-sum-by-cs_balotiy-acwn | Let n be the number of nodes in the graph, and let m be the number of edges in the graph.
Time complexity: O(n+m)
Space complexity: O(n+m)
Code | cs_balotiya | NORMAL | 2024-12-21T08:24:33.218549+00:00 | 2024-12-21T08:24:33.218549+00:00 | 17 | false | Let n be the number of nodes in the graph, and let m be the number of edges in the graph.
- Time complexity: O(n+m)
- Space complexity: O(n+m)
# Code
```cpp []
class Solution {
public:
long long dfs(int node, int parent, const vector<vector<int>>& adj, vector<int>& values, int& res, int k) {
long long preSum = values[node];
for (int child : adj[node]) {
if (child == parent) continue;
preSum += dfs(child, node, adj, values, res, k);
}
if (preSum % k == 0) {
res++;
return 0;
}
return preSum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k, int res = 0) {
vector<vector<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
dfs(0, -1, adj, values, res, k);
return res;
}
};
``` | 3 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Efficient DFS-Based Solution to Count K-Divisible Components in a Tree (O(n) Time Complexity) | efficient-dfs-based-solution-to-count-k-k1mt4 | IntuitionThe problem involves finding the number of connected components in a tree where the sum of node values in the component is divisible by k.
The intuitio | Hexagon_6_ | NORMAL | 2024-12-21T07:25:50.226043+00:00 | 2024-12-21T07:25:50.226043+00:00 | 24 | false | # Intuition
The problem involves finding the number of connected components in a tree where the sum of node values in the component is divisible by `k`.
The intuition is to use Depth First Search (DFS) to traverse the graph and calculate the sum of values for each subtree. Whenever a subtree's sum is divisible by `k`, it can be treated as a separate component.
# Approach
1. **Graph Representation:** Represent the tree using an adjacency list for efficient traversal.
2. **DFS Traversal:** Use DFS to calculate the sum of values for each subtree:
- Start at the root (node `0`).
- Traverse all its connected nodes recursively.
- Accumulate the sum of values for the current subtree.
3. **Component Check:** During the DFS traversal, if the sum of a subtree is divisible by `k`, increment the count of components (`ans`) and reset the subtree's sum to `0`.
4. **Edge Case:** Ensure the algorithm handles disconnected components by starting DFS from any unvisited node.
# Complexity
- **Time Complexity:**
$$O(n)$$
Since we traverse each node and edge exactly once using DFS.
- **Space Complexity:**
$$O(n)$$
For the adjacency list and the recursion stack in the worst case.
# Code
```cpp
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
// Build adjacency list
vector<vector<int>> adj(n);
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0], v = edges[i][1];
adj[u].push_back(v);
adj[v].push_back(u);
}
// Visited array to track visited nodes
vector<int> vis(n, 0);
int ans = 0; // To store the count of k-divisible components
// DFS function
auto dfs = [&](int root, auto& dfs) -> long long {
vis[root] = 1; // Mark the current node as visited
long long sum = values[root]; // Start with the current node's value
for (auto i : adj[root]) {
if (!vis[i]) {
sum += dfs(i, dfs); // Add values from connected nodes
}
}
// If the subtree sum is divisible by k, count it as a separate component
if (sum % k == 0) {
ans++; // Increment the component count
return 0; // Reset the sum for this subtree
}
return sum; // Return the sum of values for this subtree
};
// Start DFS from node 0
dfs(0, dfs);
return ans; // Return the total count of k-divisible components
}
};
| 3 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Easy Solution || C++ || DFS | easy-solution-dfs-by-shishirrsiam-3wjz | if it's help, please up ⬆ vote! ❤️Code | shishirRsiam | NORMAL | 2024-12-21T04:21:51.799832+00:00 | 2024-12-21T04:22:20.566356+00:00 | 558 | false | # if it's help, please up ⬆ vote! ❤️
# Code
```cpp []
class Solution {
public:
int ans = 0;
unordered_map<int, vector<int>> adj;
long dfs(int node, int parent, int &k, vector<int>& values)
{
long subTreeSum = values[node];
for(auto &child : adj[node])
{
if(child != parent)
subTreeSum += dfs(child, node, k, values);
}
if(subTreeSum % k == 0)
ans += 1, subTreeSum = 0;
return subTreeSum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k)
{
for(auto &ed : edges)
{
int u = ed[0], v = ed[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0, -1, k, values);
return ans;
}
};
``` | 3 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 4 |
maximum-number-of-k-divisible-components | EASY and Simple TREE | easy-and-simple-tree-by-codewithsparsh-hmh9 | IntuitionThe problem requires splitting a graph into the maximum number of connected components where the sum of node values in each component is divisible by ( | CodeWithSparsh | NORMAL | 2024-12-21T02:26:05.122015+00:00 | 2024-12-21T02:26:32.227306+00:00 | 533 | false |
# Intuition
The problem requires splitting a graph into the maximum number of connected components where the sum of node values in each component is divisible by \(k\). This suggests a **tree traversal** approach to accumulate the values of nodes and check divisibility conditions. Depth-first search (DFS) is particularly suitable for this type of traversal, as it allows us to explore the tree recursively and aggregate results efficiently.
---
# Approach
1. **Graph Representation**: Represent the graph as an adjacency list for efficient traversal.
2. **DFS Traversal**:
- Traverse the tree using DFS starting from an arbitrary root (e.g., node 0).
- Maintain the cumulative sum of values for each subtree.
- Check if the cumulative sum is divisible by \(k\). If yes:
- Increment the component counter.
- Reset the sum to 0 for the current subtree.
3. **Edge Case**: If the root itself forms a valid divisible component, ensure it is handled appropriately.
4. **Count Components**: The result is the total number of components found during the traversal.
---
# Complexity
- **Time Complexity**: \(O(n)\)
- Each node and edge is visited once during the DFS traversal.
- **Space Complexity**: \(O(n)\)
- Space is used for the adjacency list and the recursion stack.
---
# Code Explanation
The provided code implements this approach efficiently. Below is the Java implementation:
---
# Code
```java []
import java.util.*;
class Solution {
private Map<Integer, List<Integer>> adj; // Adjacency list to represent the tree
private int comp; // Counter for components divisible by k
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
adj = new HashMap<>();
comp = 0;
// Build the adjacency list
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adj.computeIfAbsent(u, key -> new ArrayList<>()).add(v);
adj.computeIfAbsent(v, key -> new ArrayList<>()).add(u);
}
// Perform DFS from node 0 (assuming it is the root)
dfs(0, -1, values, k);
return comp;
}
private int dfs(int root, int parent, int[] values, int k) {
int sum = values[root]; // Start with the current node's value
// Traverse all neighbors (children in the tree)
for (int neighbor : adj.getOrDefault(root, Collections.emptyList())) {
if (neighbor != parent) { // Avoid revisiting the parent
sum += dfs(neighbor, root, values, k); // Accumulate subtree sum
}
}
// Check if the current subtree's sum is divisible by k
if (sum % k == 0) {
comp++; // Increment component count
return 0; // Reset the sum for the current subtree
}
return sum % k; // Return the remainder to the parent
}
}
```
```dart []
import 'dart:collection';
class Solution {
Map<int, List<int>> adj = {};
int comp = 0;
int maxKDivisibleComponents(int n, List<List<int>> edges, List<int> values, int k) {
// Build adjacency list
for (var edge in edges) {
adj.putIfAbsent(edge[0], () => []).add(edge[1]);
adj.putIfAbsent(edge[1], () => []).add(edge[0]);
}
// Start DFS from node 0
dfs(0, -1, values, k);
return comp;
}
int dfs(int node, int parent, List<int> values, int k) {
int sum = values[node];
for (var neighbor in adj[node] ?? []) {
if (neighbor != parent) {
sum += dfs(neighbor, node, values, k);
}
}
if (sum % k == 0) {
comp++;
return 0;
}
return sum % k;
}
}
```
```python []
from collections import defaultdict
class Solution:
def maxKDivisibleComponents(self, n, edges, values, k):
adj = defaultdict(list)
self.comp = 0
# Build adjacency list
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def dfs(node, parent):
total = values[node]
for neighbor in adj[node]:
if neighbor != parent:
total += dfs(neighbor, node)
if total % k == 0:
self.comp += 1
return 0
return total % k
dfs(0, -1)
return self.comp
```
```javascript []
class Solution {
constructor() {
this.adj = new Map();
this.comp = 0;
}
maxKDivisibleComponents(n, edges, values, k) {
// Build adjacency list
edges.forEach(([u, v]) => {
if (!this.adj.has(u)) this.adj.set(u, []);
if (!this.adj.has(v)) this.adj.set(v, []);
this.adj.get(u).push(v);
this.adj.get(v).push(u);
});
const dfs = (node, parent) => {
let sum = values[node];
(this.adj.get(node) || []).forEach((neighbor) => {
if (neighbor !== parent) {
sum += dfs(neighbor, node);
}
});
if (sum % k === 0) {
this.comp++;
return 0;
}
return sum % k;
};
dfs(0, -1);
return this.comp;
}
}
```
```cpp []
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
unordered_map<int, vector<int>> adj;
int comp = 0;
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
// Build adjacency list
for (auto& edge : edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
dfs(0, -1, values, k);
return comp;
}
private:
int dfs(int node, int parent, vector<int>& values, int k) {
int sum = values[node];
for (int neighbor : adj[node]) {
if (neighbor != parent) {
sum += dfs(neighbor, node, values, k);
}
}
if (sum % k == 0) {
comp++;
return 0;
}
return sum % k;
}
};
```
```go []
package main
func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) int {
adj := make(map[int][]int)
comp := 0
// Build adjacency list
for _, edge := range edges {
u, v := edge[0], edge[1]
adj[u] = append(adj[u], v)
adj[v] = append(adj[v], u)
}
var dfs func(node, parent int) int
dfs = func(node, parent int) int {
sum := values[node]
for _, neighbor := range adj[node] {
if neighbor != parent {
sum += dfs(neighbor, node)
}
}
if sum%k == 0 {
comp++
return 0
}
return sum % k
}
dfs(0, -1)
return comp
}
```
```kotlin []
class Solution {
private val adj = mutableMapOf<Int, MutableList<Int>>()
private var comp = 0
fun maxKDivisibleComponents(n: Int, edges: Array<IntArray>, values: IntArray, k: Int): Int {
for (edge in edges) {
adj.computeIfAbsent(edge[0]) { mutableListOf() }.add(edge[1])
adj.computeIfAbsent(edge[1]) { mutableListOf() }.add(edge[0])
}
dfs(0, -1, values, k)
return comp
}
private fun dfs(node: Int, parent: Int, values: IntArray, k: Int): Int {
var sum = values[node]
for (neighbor in adj[node] ?: emptyList()) {
if (neighbor != parent) {
sum += dfs(neighbor, node, values, k)
}
}
if (sum % k == 0) {
comp++
return 0
}
return sum % k
}
}
```
---
# Explanation of Key Steps
1. **Adjacency List Construction**:
- Each edge connects two nodes, and both directions are added to the adjacency list.
2. **DFS Logic**:
- Each node aggregates the sum of its subtree values.
- If the aggregated sum is divisible by \(k\), the subtree is considered a valid component.
3. **Component Counting**:
- For every valid subtree, the count of components is incremented.
This approach ensures efficiency and correctness, handling various tree structures and \(k\)-values. | 3 | 0 | ['Tree', 'Depth-First Search', 'C', 'C++', 'Java', 'Go', 'Python3', 'Kotlin', 'JavaScript', 'Dart'] | 0 |
maximum-number-of-k-divisible-components | Rust solution - DFS | rust-solution-dfs-by-sunjesse-wryc | Code | sunjesse | NORMAL | 2024-12-21T00:38:52.665782+00:00 | 2024-12-21T00:38:52.665782+00:00 | 113 | false | # Code
```rust []
use std::collections::HashMap;
impl Solution {
fn dfs(seen: &mut Vec<bool>, G: &HashMap<usize, Vec<usize>>, values: &mut Vec<i32>, k: &i32, u: usize, ans: &mut i32) -> i32 {
seen[u] = true;
if !G.contains_key(&u) {
*ans += 1;
return 0;
}
for v in G[&u].iter() {
if !seen[*v] {
values[u] += Self::dfs(seen, G, values, k, *v, ans) % k;
}
}
if values[u] % k == 0 {
*ans += 1;
return 0;
}
values[u]
}
pub fn max_k_divisible_components(n: i32, edges: Vec<Vec<i32>>, mut values: Vec<i32>, k: i32) -> i32 {
let mut G: HashMap<usize, Vec<usize>> = HashMap::with_capacity(n as usize);
for e in edges {
G.entry(e[0] as usize).or_insert(Vec::new()).push(e[1] as usize);
G.entry(e[1] as usize).or_insert(Vec::new()).push(e[0] as usize);
}
let mut seen: Vec<bool> = vec![false; n as usize];
let mut ans: i32 = 0;
Self::dfs(&mut seen, &G, &mut values, &k, 0, &mut ans);
ans
}
}
``` | 3 | 0 | ['Rust'] | 2 |
maximum-number-of-k-divisible-components | [Python3] Cut Leaf - BFS + Topological Sort - Simple Solution | python3-cut-leaf-bfs-topological-sort-si-p96b | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dolong2110 | NORMAL | 2024-03-13T15:42:33.565518+00:00 | 2024-03-13T16:46:06.568275+00:00 | 78 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n##### 1. BFS\n```\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n if n < 2: return 1\n cnt = 0\n g = defaultdict(set)\n for u, v in edges:\n g[u].add(v)\n g[v].add(u)\n \n dq = collections.deque(u for u, vs in g.items() if len(vs) == 1) \n while dq:\n u = dq.popleft()\n v = next(iter(g[u])) if g[u] else -1\n if v >= 0 : g[v].remove(u)\n if values[u] % k == 0 : cnt += 1\n else: values[v] += values[u]\n if v >= 0 and len(g[v]) == 1 : dq.append(v)\n\n return cnt\n```\n\n##### 2. Topological Sort\n\n```\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n if n < 2: return 1\n cnt = 0\n g = defaultdict(list)\n in_degree = [0 for _ in range(n)]\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n in_degree[u] += 1\n in_degree[v] += 1\n dq = collections.deque(u for u in range(n) if in_degree[u] == 1)\n while dq:\n u = dq.popleft()\n in_degree[u] -= 1\n add = 0\n if values[u] % k == 0 : cnt += 1\n else: add = values[u]\n for v in g[u]:\n if in_degree[v] == 0: continue\n in_degree[v] -= 1\n values[v] += add\n if in_degree[v] == 1: dq.append(v)\n return cnt\n```\n\nThis is similar to this [problem](https://leetcode.com/problems/create-components-with-same-value/solutions/4871128/python3-math-topological-sort-simple-solution/) | 3 | 0 | ['Hash Table', 'Tree', 'Breadth-First Search', 'Topological Sort', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | [C++|Java|Python3] DFS | cjavapython3-dfs-by-ye15-r4bo | C++\n\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n vector<vector<int>> | ye15 | NORMAL | 2023-10-03T01:49:27.045794+00:00 | 2023-10-03T01:49:27.045815+00:00 | 64 | false | C++\n```\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n vector<vector<int>> tree(n); \n for (auto& e : edges) {\n tree[e[0]].push_back(e[1]); \n tree[e[1]].push_back(e[0]); \n }\n \n function<long(int, int)> fn = [&](int u, int p) {\n for (auto& v : tree[u]) \n if (v != p) values[u] = (values[u] + fn(v, u)) % k; \n return values[u]; \n }; \n \n fn(0, -1); \n return count_if(values.begin(), values.end(), [&](auto& x) { return x % k == 0; }); \n }\n};\n```\nJava\n```\nclass Solution {\n \n private long fn(int u, int p, List<Integer>[] tree, int[] values, int k) {\n for (var v : tree[u]) \n if (v != p) values[u] = (int) ((values[u] + fn(v, u, tree, values, k)) % k); \n return values[u]; \n }\n \n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n List<Integer>[] tree = new ArrayList[n]; \n Arrays.setAll(tree, x -> new ArrayList()); \n for (var e : edges) {\n tree[e[0]].add(e[1]); \n tree[e[1]].add(e[0]); \n }\n fn(0, -1, tree, values, k); \n return (int) IntStream.of(values).filter(x -> x % k == 0).count(); \n }\n}\n```\nPython3\n```\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n tree = [[] for _ in range(n)]\n for u, v in edges: \n tree[u].append(v)\n tree[v].append(u)\n \n def fn(u, p): \n """Return sum of node values in subtree."""\n for v in tree[u]: \n if v != p: values[u] += fn(v, u)\n return values[u]\n \n fn(0, -1)\n return sum(x % k == 0 for x in values)\n\n``` | 3 | 0 | ['C', 'Java', 'Python3'] | 1 |
maximum-number-of-k-divisible-components | Easy Implementation | easy-implementation-by-talib5-t43b | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | talib5 | NORMAL | 2023-09-30T17:36:24.589581+00:00 | 2023-09-30T17:36:24.589602+00:00 | 36 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int dfs(int node, int parent, vector<vector<int>>& adj, vector<int>& values, int k, int& ans) {\n int compSum = values[node];\n\n for (int neighbor : adj[node]) {\n if (neighbor == parent) continue; // Skip the parent node\n\n compSum += dfs(neighbor, node, adj, values, k, ans);\n }\n\n if (compSum % k == 0) {\n // If the component sum is divisible by k, mark it as valid\n ans++;\n compSum = 0; // Reset the component sum to start a new component\n }\n\n return compSum;\n }\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n unordered_map<int, int> compSums; // Map to store the sum of values for each component\n vector<vector<int>> adj(n); // Adjacency list representation of the tree\n\n // Build the adjacency list\n for (vector<int>& edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n\n int ans = 0; // Maximum number of components in any valid split\n\n // DFS function to traverse the tree and calculate component sums\n int rootCompSum = dfs(0, -1, adj, values, k, ans);\n\n if (rootCompSum % k == 0) {\n // If the root component sum is divisible by k, mark it as valid\n ans++;\n }\n\n return ans - 1;\n }\n};\n``` | 3 | 0 | ['Backtracking', 'Tree', 'Depth-First Search', 'Graph', 'Recursion', 'C++'] | 1 |
maximum-number-of-k-divisible-components | ✅☑[C++] ||Beats 95% || EXPLAINED🔥 | c-beats-95-explained-by-marksphilip31-vqgo | \n# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approach\n(Also explained in the code)\n\n1. The function maxKDivisibleComponents takes several inputs: the number | MarkSPhilip31 | NORMAL | 2023-09-30T16:07:36.625677+00:00 | 2023-09-30T16:15:53.017523+00:00 | 364 | false | \n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approach\n***(Also explained in the code)***\n\n1. The function `maxKDivisibleComponents` takes several inputs: the number of nodes `n`, a list of edges, a list of values associated with each node, and an integer `k`.\n\n1. It uses dynamic programming to calculate `dp` values for each node and a tree structure represented by the `nodes` vector.\n\n1. It counts the number of nodes in the tree whose `dp` values are divisible by `k` and increments the `ans` variable accordingly.\n\n1. The depth-first search (DFS) function `dfs` recursively computes `dp` values for nodes and updates the answer based on the divisibility of these values by `k`.\n\n---\n\n\n\n# Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(n)$$\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n // Initialize a dynamic programming array and a vector to represent the tree nodes.\n vector<long long> dp(n, 0);\n vector<vector<int>> nodes(n);\n \n // Build the tree structure from the edges.\n for (int i = 0; i < edges.size(); ++i) {\n nodes[edges[i][0]].push_back(edges[i][1]);\n nodes[edges[i][1]].push_back(edges[i][0]);\n }\n \n int ans = 0; // Initialize the answer to 0.\n \n // Define a depth-first search (DFS) function.\n function<void(int, int)> dfs = [&](int u, int p) {\n dp[u] = 1ll * values[u]; // Initialize the dp value for the current node.\n \n for (int v : nodes[u]) {\n if (v == p) continue; // Skip the parent node.\n \n dfs(v, u); // Recursively explore the child node.\n \n if (dp[v] % k == 0) {\n ++ans; // If the child\'s dp value is divisible by k, increment the answer.\n } else {\n dp[u] += dp[v]; // Otherwise, accumulate the dp values.\n dp[u] %= k;\n }\n }\n };\n \n dfs(0, 0); // Start DFS from the root node (0).\n return ans + 1; // Return the answer, incrementing it by 1.\n }\n};\n\n```\n\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n---\n\n | 3 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Building a Tree and using DFS to prune the tree childs | building-a-tree-and-using-dfs-to-prune-t-31ro | IntuitionBuilding a Tree and using DFS to prune the tree childs.ApproachOnce we have our tree, we start buttom up if we have a child tree that is divisble by k | youssefsaad3000 | NORMAL | 2024-12-30T19:42:12.021758+00:00 | 2024-12-30T19:42:12.021758+00:00 | 11 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Building a Tree and using DFS to prune the tree childs.
# Approach
<!-- Describe your approach to solving the problem. -->
Once we have our tree, we start buttom up if we have a child tree that is divisble by k we prune it (remove it and consider it as connected component) as we will starts from the leafs we are sure we will build the minimum divisible components
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(N+M)$$ ~ $$ O(N)$$. as `M= N-1`
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
Tree data structure space $$O(N)$$
# Code
```python3 []
from collections import defaultdict
class Solution:
def maxKDivisibleComponents(
self, n: int, edges: List[List[int]], values: List[int], k: int
) -> int:
childs = defaultdict(list)
tree = Tree.form_tree_from_edges(edges)
# print(tree.childs[0])
res = self.solve(tree, n, values, k)
return res
def solve(self, root: "Tree", n, values, k):
self.ans = 0
def helper(r):
if not r.childs:
return values[r.data]
total = values[r.data] % k
for child in r.childs:
res = helper(child)
if res % k == 0:
# let us prune
self.ans += 1
total = (total + res) % k
return total
helper(root)
return self.ans + 1
class Tree:
def __init__(self, data, childs: List["Tree"] = None):
self.data = data
if childs:
self.childs = childs
else:
self.childs = []
def __str__(self):
strr = "cur:self.data, childs:["
return strr + ", ".join(str(s.data) for s in self.childs) + "]"
@staticmethod
def form_tree_from_edges(edges) -> "Tree":
# Let s assume that 0 is always the root
childs = defaultdict(list)
for fr, tt in edges:
childs[fr].append(tt)
childs[tt].append(fr)
seen = set()
root = Tree(0)
queue = [root]
while queue:
node = queue.pop(0)
seen.add(node.data)
for child in childs[node.data]:
i = 0
if child not in seen:
curr = Tree(child)
node.childs.append(curr)
queue.append(curr)
return root
return Tree(9)
def show(self):
queue = [self.Tree]
``` | 2 | 0 | ['Python3'] | 0 |
maximum-number-of-k-divisible-components | most optimised java solution || java DFS || faster code | most-optimised-java-solution-java-dfs-fa-xd8m | import java.util.*;\n\nclass Solution {\n private int dfs(List> adj, int[] values, int k, int[] count, int curr, int parent) {\n long sum = values[cur | Seema_Kumari1 | NORMAL | 2024-12-21T13:31:17.402269+00:00 | 2024-12-21T13:31:17.402311+00:00 | 16 | false | import java.util.*;\n\nclass Solution {\n private int dfs(List<List<Integer>> adj, int[] values, int k, int[] count, int curr, int parent) {\n long sum = values[curr];\n for (int nbr : adj.get(curr)) {\n if (nbr != parent) {\n sum += dfs(adj, values, k, count, nbr, curr);\n }\n }\n sum %= k;\n if (sum == 0) count[0]++;\n return (int) sum;\n }\n\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n List<List<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n adj.add(new ArrayList<>());\n }\n for (int[] edge : edges) {\n adj.get(edge[0]).add(edge[1]);\n adj.get(edge[1]).add(edge[0]);\n }\n int[] count = {0};\n dfs(adj, values, k, count, 0, -1);\n return count[0];\n }\n} | 2 | 0 | ['Tree', 'Depth-First Search', 'Binary Tree', 'Java'] | 0 |
maximum-number-of-k-divisible-components | Not that easy but at least the code is clean | not-that-easy-but-at-least-the-code-is-c-q5ca | Code | Nade4n | NORMAL | 2024-12-21T13:34:27.705670+00:00 | 2024-12-21T13:34:27.705670+00:00 | 50 | false |
# Code
```csharp []
public class Solution {
public int MaxKDivisibleComponents(int n, int[][] edges, int[] values, int k)
{
//build adjacent list
List<int>[] graph = new List<int>[n];
foreach(var edge in edges)
{
int node1=edge[0];
int node2=edge[1];
if(graph[node1]==null)
{
graph[node1]=new List<int>();
}
if(graph[node2]==null)
{
graph[node2]=new List<int>();
}
graph[node1].Add(node2);
graph[node2].Add(node1);
}
int KDivisableComponentCount=0;
//assume zero is the root and intiall parent
DFS(0,-1);
return KDivisableComponentCount;
long DFS(int currentNode,int parentNode)
{
long SubTreeSum=values[currentNode];
if(graph[currentNode]!=null)
{
foreach(var neighbor in graph[currentNode])
{
//avoid the cycle
if(neighbor!=parentNode)
{
SubTreeSum=SubTreeSum+DFS(neighbor,currentNode);
}
}
}
if(SubTreeSum%k==0)
{
KDivisableComponentCount++;
}
return SubTreeSum;
}
}
}
``` | 2 | 0 | ['C#'] | 0 |
maximum-number-of-k-divisible-components | DFS | dfs-by-ahmedsayed1-iabl | ExplainingLets starts with the root 0 and make dfs and for every summation of values subtree of current node if its divisable by k increase my ans and make the | AhmedSayed1 | NORMAL | 2024-12-21T09:01:08.565519+00:00 | 2024-12-21T09:03:44.858585+00:00 | 44 | false | # Explaining
<h3>Lets starts with the root 0 and make dfs and for every summation of values subtree of current node if its divisable by k increase my ans and make the ret equal to 0 (that means i removed the edge between node and its parent) and when node is the root (node = 0) if the final summation is not divisable by k then decrease the answer that means i made one invalid remove</h3>
# Code
```cpp []
#define ll long long
const int N = 1e5;
vector<int>val, adj[N];
int k, ans;
ll dfs(int node = 0, int par = -1){
ll ret = val[node];
for(auto i : adj[node])
if(i != par)ret += dfs(i, node);
if(ret % k == 0)
ans++, ret = 0;
if(!node && ret % k)ans--;
return ret;
}
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k2) {
fill(adj, adj + n, vector<int>());
val = values, k = k2, ans = 0;
for(auto i : edges){
adj[i[0]].push_back(i[1]),
adj[i[1]].push_back(i[0]);
}
dfs();
return ans;
}
};
```
 | 2 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Go Solution (bahasa indonesia) | go-solution-by-anastasyawlf-4tr3 | Approach
DFS (Depth-First Search):
Hitung total nilai di subtree setiap node.
Pastikan subtree bisa menjadi komponen yang habis dibagi 𝑘.
Validasi Komponen: | anastasyawlf | NORMAL | 2024-12-21T08:45:50.264299+00:00 | 2024-12-21T08:49:33.004584+00:00 | 79 | false | # Approach
<!-- Describe your approach to solving the problem. -->
1) DFS (Depth-First Search):
- Hitung total nilai di subtree setiap node.
- Pastikan subtree bisa menjadi komponen yang habis dibagi 𝑘.
2) Validasi Komponen:
- Cek apakah dengan memotong suatu edge, subtree yang dihasilkan valid.
3) Optimasi:
- Lakukan eksplorasi semua kemungkinan pemotongan dengan efisien.
# Code
```golang []
func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) int {
//representasi graf dari edges
graph := make([][]int, n)
for _, edge := range edges {
a, b := edge[0], edge[1]
graph[a] = append(graph[a], b)
graph[b] = append(graph[b], a)
}
result := 0
//DFS untuk menghitung jumlah komponen valid
var dfs func(node, parent int) int
dfs = func(node, parent int) int {
sum := values[node] //total nilai subtree
//traverse anak2 node saat ini
for _, neighbor := range graph[node] {
if neighbor != parent {
sum += dfs(neighbor, node)
}
}
//jika total nilai subtree habis dibagi k, komponen valid
if sum%k == 0 {
result++
return 0
}
return sum
}
dfs(0,-1) //mulai dari root (node 0)
return result
}
``` | 2 | 0 | ['Go'] | 0 |
maximum-number-of-k-divisible-components | 🌳 Breaking the Tree into Divisible Components 🌟|| Beats 100% ✅ || JAVA ✅ | breaking-the-tree-into-divisible-compone-o5ex | IntuitionThe problem is to split a tree into the maximum number of connected components such that the sum of the node values in each component is divisible by ( | code-shinobi | NORMAL | 2024-12-21T07:20:46.559030+00:00 | 2024-12-21T07:20:46.559030+00:00 | 133 | false | # Intuition
The problem is to split a tree into the maximum number of connected components such that the sum of the node values in each component is divisible by \(k\).
The key observation is that we can use a **DFS traversal** to compute the sum of the values in each subtree. By checking the divisibility of these sums during the traversal, we can incrementally count the valid components.
---
# Approach
1. **Graph Representation**:
- Represent the tree as an **adjacency list** for efficient traversal.
- Each edge is bi-directional, connecting two nodes.
2. **Depth-First Search (DFS)**:
- Start the DFS from the root node (node 0).
- For each node:
- Compute the sum of its subtree values, including its own value.
- Check if the subtree sum is divisible by \(k\).
- If true, increment the `componentCount` and reset the sum for this subtree, as it forms a valid component.
3. **Edge Cases**:
- \(k = 1\): All sums are divisible, so the number of components equals the number of nodes.
4. **Output**:
- Return the total count of \(k\)-divisible components after completing the DFS.
---
# Code
```java []
import java.util.*;
class Solution {
int componentCount = 0;
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
// Create an adjacency list for the graph
List<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int node1 = edge[0];
int node2 = edge[1];
adjList[node1].add(node2);
adjList[node2].add(node1);
}
// Start DFS traversal from node 0
boolean[] visited = new boolean[n];
dfs(0, -1, adjList, values, k, visited);
// Return the total number of components
return componentCount;
}
private int dfs(int current, int parent, List<Integer>[] adjList, int[] values, int k, boolean[] visited) {
visited[current] = true;
// Initialize the sum of the current subtree with the value of the current node
int subtreeSum = values[current];
// Traverse all neighbors (children)
for (int neighbor : adjList[current]) {
if (neighbor != parent && !visited[neighbor]) { // Avoid revisiting the parent node
// Recursively calculate the subtree sum for the child node
subtreeSum += dfs(neighbor, current, adjList, values, k, visited);
}
}
subtreeSum = subtreeSum % k;
// Check if the subtree sum is divisible by k
if (subtreeSum == 0) {
componentCount++; // Increment the component count
return 0; // Reset the sum for this subtree as it forms a valid component
}
// Return the subtree sum to the parent
return subtreeSum;
}
}
``` | 2 | 0 | ['Java'] | 0 |
maximum-number-of-k-divisible-components | Java code | java-code-by-ayeshakhan7-uofd | Code | ayeshakhan7 | NORMAL | 2024-12-21T07:17:34.459544+00:00 | 2024-12-21T07:17:34.459544+00:00 | 184 | false |
# Code
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
// adjacency list from edges
List<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int node1 = edge[0];
int node2 = edge[1];
adjList[node1].add(node2);
adjList[node2].add(node1);
}
int[] componentCount = new int[1];
dfs(0, -1, adjList, values, k, componentCount);
return componentCount[0];
}
long dfs(int currentNode, int parentNode, List<Integer>[] adjList,
int[] nodeValues, int k, int[] componentCount) {
long sum = 0;
for (int neighborNode : adjList[currentNode]) {
if (neighborNode != parentNode) {
//check the sum
sum += dfs(neighborNode,currentNode,adjList,nodeValues,k,componentCount);
}
}
sum += nodeValues[currentNode];
if (sum%k == 0) {
componentCount[0]++;
sum=0;
}
return sum;
}
}
``` | 2 | 0 | ['Java'] | 0 |
maximum-number-of-k-divisible-components | [Javascript] DFS O(n) / O(n) | javascript-dfs-on-on-by-_savely-bz2g | Intuitionevery subtree with the sum of nodes values divisible by K will represent a separate componentCode | _savely | NORMAL | 2024-12-21T06:13:22.429707+00:00 | 2024-12-21T06:13:22.429707+00:00 | 73 | false | # Intuition
every subtree with the sum of nodes values divisible by K will represent a separate component
# Code
```javascript []
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} values
* @param {number} k
* @return {number}
*/
var maxKDivisibleComponents = function(n, edges, values, k) {
const adj = Array.from({length : n}, () => new Set());
for(const [u, v] of edges) {
adj[u].add(v);
adj[v].add(u);
}
let components = 0;
const dfs = (node, parent = null) => {
let sum = values[node];
for(const u of adj[node]) {
if(u === parent) continue;
sum += dfs(u, node);
}
components += sum % k === 0 ? 1 : 0;
return sum;
}
dfs(0);
return components;
}
``` | 2 | 0 | ['Tree', 'Depth-First Search', 'JavaScript'] | 0 |
maximum-number-of-k-divisible-components | Follow for more easy solution | follow-for-more-easy-solution-by-dev_bha-ndni | Code | dev_bhatt202 | NORMAL | 2024-12-21T05:51:48.730595+00:00 | 2024-12-21T05:51:48.730595+00:00 | 29 | false |
# Code
```java []
import java.util.*;
class Solution {
private long cnt = 0;
private void getSubtree(int node, List<List<Integer>> adj, int parent, long[] subtree) {
if (adj.get(node).size() == 1 && adj.get(node).get(0) == parent) return;
for (int neighbor : adj.get(node)) {
if (neighbor != parent) {
getSubtree(neighbor, adj, node, subtree);
subtree[node] += subtree[neighbor];
}
}
}
private void dfs(int node, List<List<Integer>> adj, int parent, long[] subtree, int k) {
if (adj.get(node).size() == 1 && adj.get(node).get(0) == parent) return;
for (int neighbor : adj.get(node)) {
if (neighbor != parent) {
long parSubtree = subtree[node] - subtree[neighbor];
long childSubtree = subtree[neighbor];
if (parSubtree % k == 0 && childSubtree % k == 0) {
cnt++;
subtree[node] -= subtree[neighbor];
} else {
subtree[neighbor] = subtree[node];
}
dfs(neighbor, adj, node, subtree, k);
}
}
}
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
long[] subtree = new long[n];
for (int i = 0; i < n; i++) subtree[i] = values[i];
getSubtree(0, adj, -1, subtree);
dfs(0, adj, -1, subtree, k);
return (int) (cnt + 1);
}
}
``` | 2 | 0 | ['Tree', 'Depth-First Search', 'Java'] | 1 |
maximum-number-of-k-divisible-components | Here Comes Easiest Solution 🥳🥳 | here-comes-easiest-solution-by-sarangkal-m2ym | IntuitionThe goal is to maximize the number of connected components in the tree such that the sum of node values in each component is divisible by k. To achieve | Sarangkale66 | NORMAL | 2024-12-21T05:33:34.867348+00:00 | 2024-12-21T05:33:34.867348+00:00 | 260 | false | # Intuition
The goal is to maximize the number of connected components in the tree such that the sum of node values in each component is divisible by **k**. To achieve this, we explore the tree using Depth-First Search **(DFS)** and leverage modular arithmetic to determine divisibility conditions.
# Approach
Tree Representation:
Represent the given tree using an adjacency list to efficiently traverse its structure.
##### DFS Traversal:
1. Start the traversal from the root node (node 0).
2. For each child node, recursively compute the sum of the subtree rooted at the child.
3. If the subtree sum modulo k equals 0, it can be split as a new component, and the component count is incremented.
Otherwise, propagate the sum to the parent node.
4. Handle Remaining Nodes:
5. After completing the traversal, check the total sum of the tree. If it is divisible by k, increment the component count.
Final Count:
Return the total number of components formed.
# Complexity
- Time complexity: **𝑂( N + E )**
Each node and edge is visited once during the DFS traversal.
- Space complexity: **O( N )**
For the adjacency list representation and the visited array
# Code
```cpp []
class Solution {
private:
int comp = 0;
long DFS(int u, int k, vector<int> adj[], vector<bool>& visited,
vector<int>& values) {
visited[u] = true;
long sum = 0;
for (int v : adj[u]) {
if (!visited[v]) {
long vSum = DFS(v, k, adj, visited, values);
if (vSum % k == 0) {
comp += 1;
} else {
sum += vSum;
}
}
}
sum += values[u];
return sum;
}
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges,
vector<int>& values, int k) {
vector<int> adj[n];
for (vector<int> x : edges) {
int u = x[0];
int v = x[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<bool> visited(n, false);
long sum = DFS(0, k, adj, visited, values);
if (sum % k == 0)
comp += 1;
return comp;
}
};
```
```java []
import java.util.*;
class Solution {
private int comp = 0;
private long DFS(int u, int k, List<Integer>[] adj, boolean[] visited, int[] values) {
visited[u] = true;
long sum = 0;
for (int v : adj[u]) {
if (!visited[v]) {
long vSum = DFS(v, k, adj, visited, values);
if (vSum % k == 0) {
comp += 1;
} else {
sum += vSum;
}
}
}
sum += values[u];
return sum;
}
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
List<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adj[u].add(v);
adj[v].add(u);
}
boolean[] visited = new boolean[n];
long sum = DFS(0, k, adj, visited, values);
if (sum % k == 0) {
comp += 1;
}
return comp;
}
}
```
```javascript []
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} values
* @param {number} k
* @return {number}
*/
var maxKDivisibleComponents = function(n, edges, values, k) {
let comp = 0;
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u);
}
const visited = new Array(n).fill(false);
const DFS = (u) => {
visited[u] = true;
let sum = 0;
for (const v of adj[u]) {
if (!visited[v]) {
const vSum = DFS(v);
if (vSum % k === 0) {
comp += 1;
} else {
sum += vSum;
}
}
}
sum += values[u];
return sum;
};
const totalSum = DFS(0);
if (totalSum % k === 0) {
comp += 1;
}
return comp;
};
```
```Typescript []
function maxKDivisibleComponents(n: number, edges: number[][], values: number[], k: number): number {
let comp = 0;
const adj: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u);
}
const visited: boolean[] = new Array(n).fill(false);
const DFS = (u: number): number => {
visited[u] = true;
let sum = 0;
for (const v of adj[u]) {
if (!visited[v]) {
const vSum = DFS(v);
if (vSum % k === 0) {
comp++;
} else {
sum += vSum;
}
}
}
sum += values[u];
return sum;
};
const totalSum = DFS(0);
if (totalSum % k === 0) {
comp++;
}
return comp;
}
```
```Python []
class Solution:
def __init__(self):
self.comp = 0
def DFS(self, u, k, adj, visited, values):
visited[u] = True
total_sum = 0
for v in adj[u]:
if not visited[v]:
v_sum = self.DFS(v, k, adj, visited, values)
if v_sum % k == 0:
self.comp += 1
else:
total_sum += v_sum
total_sum += values[u]
return total_sum
def maxKDivisibleComponents(self, n, edges, values, k):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
visited = [False] * n
total_sum = self.DFS(0, k, adj, visited, values)
if total_sum % k == 0:
self.comp += 1
return self.comp
```
```Python3 []
from typing import List
class Solution:
def __init__(self):
self.comp = 0
def DFS(self, u: int, k: int, adj: List[List[int]], visited: List[bool], values: List[int]) -> int:
visited[u] = True
total_sum = 0
for v in adj[u]:
if not visited[v]:
v_sum = self.DFS(v, k, adj, visited, values)
if v_sum % k == 0:
self.comp += 1
else:
total_sum += v_sum
total_sum += values[u]
return total_sum
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
visited = [False] * n
total_sum = self.DFS(0, k, adj, visited, values)
if total_sum % k == 0:
self.comp += 1
return self.comp
``` | 2 | 0 | ['Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript'] | 0 |
maximum-number-of-k-divisible-components | Simple code with detailed explanation. (I bet you will understand this :)) | simple-code-with-detailed-explanation-i-3mggd | IntuitionThe problem involves finding the maximum number of connected components in a tree such that the sum of the values in each component is divisible by k. | nishita_shah1 | NORMAL | 2024-12-21T04:17:44.956798+00:00 | 2024-12-21T04:17:44.956798+00:00 | 46 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem involves finding the maximum number of connected components in a tree such that the sum of the values in each component is divisible by k. A connected component can be formed by removing edges in the tree. To solve this, the key is to utilize Depth First Search (DFS) to calculate the sum of values in subtrees and determine when to cut edges to form such components.
# Approach
<!-- Describe your approach to solving the problem. -->
**Step 1: Representing the Tree**
Trees are typically represented as an adjacency list for easy traversal.
Given the list of edges, we convert them into an adjacency list.
For example, if we have edges:
```
edges = {{0, 1}, {1, 2}, {1, 3}}
```
The adjacency list would be:
```
adj[0] = [1]
adj[1] = [0, 2, 3]
adj[2] = [1]
adj[3] = [1]
```
**Step 2: Traversing the Tree**
- **Start from the root node:** The tree traversal begins at node 0 (or any arbitrary root).
Use Depth First Search (DFS) to explore each child recursively.
During traversal, we compute the sum of values in the subtree rooted at the current node.
- **Pass the parent node:** To avoid revisiting the parent node in an undirected tree, pass the parent as a parameter to the DFS function.
This ensures the traversal only proceeds towards children.
**Step 3: Computing Subtree Sums**
- **Track the sum for the current subtree:**
1. At each node, maintain a variable sum that stores the sum of the subtree rooted at that node.
Recursively calculate child subtree sums:
2. For each child (neighbor) of the current node (except its parent), recursively call DFS.
Add the returned value (modulo k) to the current node's sum.
Include the current node's value:
3. Add the value of the current node to the sum.
Take modulo k for the sum:
4. At each step, compute sum % k. This ensures that the sum remains within bounds and we only focus on divisibility by k.
5. (a+b)%k = (a%k + b%k)%k , so instead of adding a+b and then taking modulo we will do (a%k + b%k)%k because many time a+b becomes a very large number.
**Step 4: Divisibility Check**
After calculating the sum for the subtree rooted at the current node:
1. If sum % k == 0, it means the subtree forms a valid k-divisible component.
2. Increment the component count (cnt) and "remove" this subtree conceptually.
3. Return the remaining sum (sum % k) to the parent:
4. The parent uses this returned value to calculate its own subtree sum.
**Step 5: Complete the Process**
Once the DFS completes for the entire tree, the variable cnt will hold the maximum number of k-divisible components.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- **Building the Adjacency List:**
1. You iterate through all the edges in the graph to build the adjacency list.
2. For n nodes, the number of edges in a tree is n−1 (since a tree has n−1 edges).
3. Iterating over all edges to create the adjacency list takes O(n−1), which is O(n).
Depth-First Search (DFS) Traversal:
- **DFS explores each node once and each edge once.**
1. For each node, you perform a constant amount of work (e.g., summing values, checking divisibility, etc.), so the work per node is O(1).
2. Since there are n nodes and n−1 edges, the DFS traversal takes O(n+(n−1))=O(2n−1), which simplifies to O(n).
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1. Adjacency List Storage:O(n).
2. Recursive Call Stack:O(h), where h is the height of the tree (O(logn) for balanced, O(n) for skewed).
3. Total: O(n).
# Code
```cpp []
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
// step 1: creating adjacency list from edges
vector<vector<int>>adj(n);
for(auto edge:edges){
int node1=edge[0];
int node2=edge[1];
adj[node1].push_back(node2);
adj[node2].push_back(node1);
}
int cnt=0; // counter for component
// step 2: start dfs traversal from node 0
dfs(0,-1,adj,values,k,cnt);
return cnt;
}
int dfs(int currnode,int parentnode,vector<vector<int>>& adj,vector<int>& values, int k,int& cnt){
int sum=0; //sum for current subtree
// traverse all neighbors
for(auto neighbor:adj[currnode] ){
if(neighbor !=parentnode){
sum+=dfs(neighbor,currnode,adj,values,k, cnt);
sum=sum%k;
}
}
sum+=values[currnode];
sum%=k;
if(sum==0)cnt++;
return sum;
}
};
``` | 2 | 0 | ['Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | DFS || Hard to get Intuition || ---- | dfs-hard-to-get-intuition-by-jayavenkate-fnck | IntuitionApproachComplexity
Time complexity: O(N)
Space complexity: O(N)
Code | jayavenkatesh | NORMAL | 2024-12-21T03:42:20.038776+00:00 | 2024-12-21T03:42:20.038776+00:00 | 11 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
static int ans;
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
List<List<Integer>> adj = new ArrayList();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList());
}
for (int[] arr : edges) {
int a = arr[0];
int b = arr[1];
adj.get(a).add(b);
adj.get(b).add(a);
}
ans = 0;
dfs(adj, values, 0, -1, k);
return ans;
}
int dfs(List<List<Integer>> adj, int[] values, int cur, int parent, int k) {
int val = values[cur];
List<Integer> list = adj.get(cur);
for (int i : list) {
if (i != parent) {
val += dfs(adj, values, i, cur, k);
}
}
if (val % k == 0) {
ans++;
return 0;
}
return val%k;
}
}
``` | 2 | 0 | ['Depth-First Search', 'Java'] | 0 |
maximum-number-of-k-divisible-components | Swift | DFS | swift-dfs-by-noahfeld-j62h | Complexity
Time complexity: O(n)
Space complexity: O(n)
Code | noahfeld | NORMAL | 2024-12-21T03:30:18.392465+00:00 | 2024-12-21T03:30:18.392465+00:00 | 49 | false | # Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```swift []
class Solution {
func maxKDivisibleComponents(_ n: Int, _ edges: [[Int]], _ values: [Int], _ k: Int) -> Int {
var adj = [[Int]](repeating: [], count: n)
for edge in edges {
let u = edge[0], v = edge[1]
adj[u].append(v)
adj[v].append(u)
}
var components = 0
func dfs(_ node: Int, _ parent: Int) -> Int {
var sum = values[node]
for child in adj[node] where child != parent {
sum += dfs(child, node)
}
if sum % k == 0 { components += 1 }
return sum
}
dfs(0, -1)
return components
}
}
``` | 2 | 0 | ['Swift'] | 0 |
maximum-number-of-k-divisible-components | Beats 53%, Enough for interviews...Maybe! | beats-53-enough-for-interviewsmaybe-by-v-u4xp | IntuitionEven though this seems like a tree, let's consider this a Graph and a simple dfs with a carry forward would workApproachdfs starting from any node woul | vtkp | NORMAL | 2024-12-21T02:58:36.696065+00:00 | 2024-12-21T02:58:36.696065+00:00 | 119 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Even though this seems like a tree, let's consider this a Graph and a simple dfs with a carry forward would work
# Approach
<!-- Describe your approach to solving the problem. -->
dfs starting from any node would do the same job since we are depending on the visited matrix.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
# Code
```cpp []
class Solution {
public:
int ans = 0;
long dfs(int node, vector<int>& values, int k, vector<bool>& visited, vector<vector<int>>& adj) {
long carry = 0;
if(visited[node]) return 0;
visited[node] = true;
for(int next: adj[node]) {
if(next == node) continue;
carry += dfs(next, values, k, visited, adj);
}
carry += values[node];
if((carry)%k == 0) {
ans++;
carry = 0;
}
return carry;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adj(n);
for(auto edge: edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
vector<bool> visited(n, false);
dfs(0, values, k, visited, adj);
return ans;
}
};
``` | 2 | 0 | ['C++'] | 0 |
maximum-number-of-k-divisible-components | DFS Technique || O(V+E) Time Complexity|| Beats 96%Users || Beginner Friendly | dfs-technique-ove-time-complexity-beats-3sa3u | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Heisenberg_wc | NORMAL | 2024-12-21T02:32:56.783434+00:00 | 2024-12-21T02:32:56.783434+00:00 | 186 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long dfs(int node,vector<vector<int>>&adj,vector<int>&vis,vector<int>&values,int &no_of_components,int k){
vis[node]=1;
long long x=0;
bool loop=false;
for(auto i:adj[node]){
if(!vis[i]){
long long a=dfs(i,adj,vis,values,no_of_components,k);
loop=true;
if(a%k==0){no_of_components++;}//If one of child is divisible by k no need to add it to the return value else we just add the number of components++;
else{x+=a;}
}
}
if(loop){return x+values[node];}//Ensure if the node contains a child
return values[node];
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adj(n);//Space Complexity:O(V+E)
for (auto& edge : edges) {//Time Complexity:O(Edges)
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
vector<int>vis(n,0);//To ensure a visited node is not visited again and again
int no_of_components=1;
for(int i=0;i<n;i++){//O(NODES)
if(!vis[i]){
int sum=dfs(i,adj,vis,values,no_of_components,k);//O(Edges)
}
}
return no_of_components;
//Time Complexity:O(V+E)
//Space Complexity:O(V+E)
//Implement Depth first Search using the necessary condition to find the max components that are divisible by k
}
};
``` | 2 | 0 | ['C++'] | 1 |
maximum-number-of-k-divisible-components | C++ Solution using DFS , Easy Approach and Explain the code | c-solution-using-dfs-easy-approach-and-e-e2ni | IntuitionThe problem requires us to maximize the number of components in a tree such that the sum of the values in each component is divisible by a given intege | Dhanu07 | NORMAL | 2024-12-21T02:26:04.655123+00:00 | 2024-12-21T02:29:22.026262+00:00 | 65 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to maximize the number of components in a tree such that the sum of the values in each component is divisible by a given integer ( k ). A tree is a connected acyclic graph, and removing edges can create multiple components. The key insight is that if the sum of values in a subtree is divisible by ( k ), we can treat that subtree as a separate component. Thus, we need to traverse the tree, calculate the sum of values for each subtree, and check the divisibility condition.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Graph Representation: We represent the tree using an adjacency list. Each node will have a list of its connected neighbors.
2. Depth-First Search (DFS): We perform a DFS traversal starting from the root node (node 0). During the traversal:
We calculate the sum of values for the subtree rooted at each node.
If the sum of values for a subtree is divisible by ( k ), we can count this subtree as a valid component and increment our component count.
If a subtree is counted as a valid component, we return 0 to indicate that this subtree can be split from its parent, effectively treating it as a separate component.
3. Return the Count: After completing the DFS traversal, we return the total count of valid components.
The DFS function is implemented as a lambda function that recursively calculates the sum of values for each subtree while keeping track of visited nodes to avoid cycles.
## Code Breakdown
code :
#include <vector>
#include <functional>
Includes: The code includes the necessary headers. vector is used for dynamic arrays, and functional is included to use std::function, which allows us to define a function type that can be used for the DFS helper function.
class Solution {
public:
int maxKDivisibleComponents(int n, std::vector<std::vector<int>>& edges, std::vector<int>& values, int k) {
Class Definition: The Solution class contains the method maxKDivisibleComponents.
Method Parameters:
n: The number of nodes in the tree.
edges: A 2D vector representing the edges of the tree.
values: A vector containing the values associated with each node.
k: The integer by which the sum of values in each component must be divisible.
// Create an adjacency list for the tree
std::vector<std::vector<int>> graph(n);
for (const auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
Graph Representation:
An adjacency list graph is created to represent the tree. It is a vector of vectors, where each index corresponds to a node and contains a list of its neighbors.
The for loop iterates through each edge and adds the connections in both directions (since the tree is undirected).
// To keep track of visited nodes
std::vector<bool> visited(n, false);
int componentCount = 0;
Visited Array: A boolean vector visited is initialized to keep track of which nodes have been visited during the DFS traversal. It is initialized to false for all nodes.
Component Count: An integer componentCount is initialized to zero. This will count the number of valid components found during the traversal.
// Helper function for DFS
std::function<long long(int)> dfs = [&](int node) -> long long {
DFS Function: A lambda function dfs is defined to perform a depth-first search. It takes an integer node as an argument and returns a long long value representing the sum of values in the subtree rooted at that node.
The & captures all variables from the surrounding scope by reference, allowing the lambda to access visited, componentCount, and values.
visited[node] = true;
long long sum = values[node]; // Start with the value of the current node
Mark as Visited: The current node is marked as visited.
Initialize Sum: The sum variable is initialized with the value of the current node.
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
sum += dfs(neighbor); // Add the sum of the subtree
}
}
Traverse Neighbors: The loop iterates through each neighbor of the current node.
Recursive DFS Call: If a neighbor has not been visited, the DFS function is called recursively on that neighbor, and its returned sum is added to the current sum.
// Check if the sum of the current component is divisible by k
if (sum % k == 0) {
componentCount++; // We can count this as a valid component
return 0; // Return 0 to indicate that this component can be split
}
Divisibility Check: After calculating the sum of the subtree, it checks if the sum is divisible by ( k ).
Increment Component Count: If it is divisible, the componentCount is incremented.
Return 0: The function returns 0 to indicate that this subtree can be treated as a separate component (effectively splitting it from its parent).
return sum; // Return the sum of this subtree
};
Return Sum: If the sum is not divisible by ( k ), the function returns the total sum of the subtree.
// Start DFS from the root node (0)
dfs(0);
Initiate DFS: The DFS traversal starts from the root node (node 0).
return componentCount; // Return the total number of valid components
}
};
Return Result: Finally, the method returns the total count of valid components that can be formed.
# Complexity
- Time Complexity: ( O(n) )
We visit each node exactly once during the DFS traversal, where ( n ) is the number of nodes in the tree.
- Space Complexity: ( O(n) )
The space complexity is primarily due to the adjacency list representation of the tree and the visited array, both of which require ( O(n) ) space.
# Code
```cpp []
#include <vector>
#include <functional>
class Solution {
public:
int maxKDivisibleComponents(int n, std::vector<std::vector<int>>& edges, std::vector<int>& values, int k) {
// Create an adjacency list for the tree
std::vector<std::vector<int>> graph(n);
for (const auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
// To keep track of visited nodes
std::vector<bool> visited(n, false);
int componentCount = 0;
// Helper function for DFS
std::function<long long(int)> dfs = [&](int node) -> long long {
visited[node] = true;
long long sum = values[node]; // Start with the value of the current node
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
sum += dfs(neighbor); // Add the sum of the subtree
}
}
// Check if the sum of the current component is divisible by k
if (sum % k == 0) {
componentCount++; // We can count this as a valid component
return 0; // Return 0 to indicate that this component can be split
}
return sum; // Return the sum of this subtree
};
// Start DFS from the root node (0)
dfs(0);
return componentCount; // Return the total number of valid components
}
};
``` | 2 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 1 |
maximum-number-of-k-divisible-components | C++ DFS | c-dfs-by-pb_matrix-5bf0 | \n#define ll long long\nclass Solution {\npublic:\n unordered_map<int,vector<int>>adj;\n vector<ll>sub;\n vector<int>val;\n int k;\n ll dfs(int n | pb_matrix | NORMAL | 2024-06-01T11:18:14.459784+00:00 | 2024-06-01T11:18:14.459808+00:00 | 78 | false | ```\n#define ll long long\nclass Solution {\npublic:\n unordered_map<int,vector<int>>adj;\n vector<ll>sub;\n vector<int>val;\n int k;\n ll dfs(int node,int par){\n ll sum=val[node];\n for(auto it:adj[node]){\n if(it!=par){\n sum+=dfs(it,node);\n }\n }\n return sub[node]=sum;\n }\n int dfs2(int node,int par){\n int div=0;\n for(auto it:adj[node]){\n if(it==par) continue;\n if((sub[it]%k)==0) div++;\n div+=dfs2(it,node);\n }\n return div; \n }\n int maxKDivisibleComponents(int n, vector<vector<int>>&v, vector<int>&valu, int kp) {\n val=valu,k=kp;\n for(auto it:v){\n int x=it[0],y=it[1];\n adj[x].push_back(y),adj[y].push_back(x);\n }\n sub.resize(n,0);\n ll x=dfs(0,-1);\n return 1+dfs2(0,-1);\n }\n};\n``` | 2 | 0 | ['Depth-First Search', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Easy Solution | With Recursive Tree | Simple | Cpp | Java | Python | 🐍 | 🔥 | easy-solution-with-recursive-tree-simple-6pxz | Approach\n\n- We go to the depth of tree and and if we find it divisible by k than , we split that edge and increment our componenets\n- else we merge(add the v | TIME2LIVE | NORMAL | 2023-10-01T13:27:44.241144+00:00 | 2023-10-01T13:27:44.241174+00:00 | 78 | false | # Approach\n\n- We go to the depth of tree and and if we find it divisible by k than , we split that edge and increment our componenets\n- else we merge(add the value) that componenet to its parent \n- we repeat this until our dfs calls end \n\n\n\n\n# Cpp\n```\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n vector<int> adj[n+1];\n for(auto it : edges){\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n int res = 0 ;\n vector<int> vis(n,0);\n vis[0]=1;\n function<int(int)> dfs = [&](int node) {\n int leaf= values[node];\n vis[node] = 1 ;\n for(auto it : adj[node]){\n if(!vis[it])\n leaf+=dfs(it);\n }\n if(leaf%k==0){\n res +=1 ;\n leaf = 0 ;\n }\n return leaf ;\n\n };\n\n dfs(0);\n if(res==0) return 1 ;\n return res ;\n }\n};\n```\n\n# Java\n\n```\n\npublic class Solution {\n public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n List<Integer>[] adj = new ArrayList[n + 1];\n for (int i = 0; i <= n; i++) {\n adj[i] = new ArrayList<>();\n }\n\n for (int[] edge : edges) {\n adj[edge[0]].add(edge[1]);\n adj[edge[1]].add(edge[0]);\n }\n\n int[] vis = new int[n];\n vis[0] = 1;\n\n int[] res = {0}; \n\n dfs(0, adj, values, k, res, vis);\n\n if (res[0] == 0) {\n return 1;\n }\n\n return res[0];\n }\n\n private int dfs(int node, List<Integer>[] adj, int[] values, int k, int[] res, int[] vis) {\n int leaf = values[node];\n vis[node] = 1;\n\n for (int it : adj[node]) {\n if (vis[it] == 0) {\n leaf += dfs(it, adj, values, k, res, vis);\n }\n }\n\n if (leaf % k == 0) {\n res[0]++;\n leaf = 0;\n }\n\n return leaf;\n }\n}\n\n```\n# Python\n```\nclass Solution:\n def maxKDivisibleComponents(self, n, edges, values, k):\n adj = [[] for _ in range(n + 1)]\n\n for edge in edges:\n adj[edge[0]].append(edge[1])\n adj[edge[1]].append(edge[0])\n\n res = [0] \n\n vis = [0] * n\n vis[0] = 1\n\n def dfs(node):\n leaf = values[node]\n vis[node] = 1\n\n for it in adj[node]:\n if vis[it] == 0:\n leaf += dfs(it)\n\n if leaf % k == 0:\n res[0] += 1\n leaf = 0\n\n return leaf\n\n dfs(0)\n\n if res[0] == 0:\n return 1\n\n return res[0]\n``` | 2 | 0 | ['Tree', 'Depth-First Search', 'Python', 'C++', 'Java'] | 0 |
maximum-number-of-k-divisible-components | simple implimentaion with DFS + modulo check | simple-implimentaion-with-dfs-modulo-che-3vkw | run dfs and collect values and keep checking the sum is devisible by k or not iff yes then replace sum with zero and keep count of these instances...\nthier is | demon_code | NORMAL | 2023-09-30T16:43:54.013319+00:00 | 2023-10-01T23:22:25.509789+00:00 | 67 | false | run dfs and collect values and keep checking the sum is devisible by k or not iff yes then replace sum with zero and keep count of these instances...\nthier is one thing that for most optimal sapration to maximize the number of components we need to start dfs from leaf node which have single connection means indegree =1\n\n```\nclass Solution {\npublic:\n \n vector<vector<int>> g;\n vector<int>a;\n vector<int> vis;\n int k=0;\n int c=0;\n int dfs(int s)\n {\n \n vis[s]=1;\n int ans=a[s];\n for(auto i: g[s])\n {\n if(vis[i]==0)\n {\n ans+=dfs(i);\n }\n }\n \n if(ans%k==0)\n {\n c++;\n ans=0;\n }\n return ans;\n }\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& v, int k1) \n {\n if(n<=1) return n;\n g.resize(n);\n k=k1;\n a=v;\n vis.resize(n,0);\n vector<int> in(n,0);\n c=0;\n for(auto i: edges)\n {\n g[i[0]].push_back(i[1]);\n g[i[1]].push_back(i[0]);\n in[i[0]]++;\n in[i[1]]++;\n }\n \n int idx=-1;\n for(int i=0; i<n; i++) \n {\n if(in[i]==1)\n {\n idx=i;\n break;\n }\n }\n \n int f=dfs(idx);\n if(f==0) return c;\n return -1;\n \n }\n};\n\n``` | 2 | 0 | ['Depth-First Search', 'C'] | 0 |
maximum-number-of-k-divisible-components | Kahn's algorithm / bfs / indegree / topological Sorting | kahns-algorithm-bfs-indegree-topological-gw09 | Intuition\n- Starting from the leaf node is the key.\n- Utilize topological sorting.\n\n# Approach\n- Calculate the indegree of each node first.\n- Begin with t | wxli3388 | NORMAL | 2023-09-30T16:06:03.619520+00:00 | 2023-09-30T16:43:26.883956+00:00 | 108 | false | # Intuition\n- Starting from the leaf node is the key.\n- Utilize topological sorting.\n\n# Approach\n- Calculate the indegree of each node first.\n- Begin with the leaf nodes.\n- If the node value % k is zero, increase the component count by one and iterate through its neighbors to reduce their indegree by 1.\n- If the node value % k is not zero, add the value of this node to all its neighbors and decrease their indegree by 1.\n- If the indegree of the neighbors is 1, add the node to the queue.\n- To avoid revisiting the same node, you can set the indegree of visited nodes to zero.\n- In the edge case, there is at least 1 component. If you can\'t form any sub-components, simply return 1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:\n graph = defaultdict(list)\n indegree = [0 for _ in range(n)]\n for s,e in edges:\n graph[s].append(e)\n graph[e].append(s)\n indegree[s]+=1\n indegree[e]+=1\n queue = deque([])\n for i in range(len(indegree)):\n if indegree[i]==1:\n queue.append(i)\n ans = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n node = queue.popleft()\n indegree[node] = 0\n if values[node]%k==0:\n ans+=1\n for neighbor in graph[node]:\n indegree[neighbor]-=1\n if indegree[neighbor]==1:\n queue.append(neighbor)\n else:\n for neighbor in graph[node]:\n indegree[neighbor]-=1\n values[neighbor]+=values[node]\n if indegree[neighbor]==1:\n queue.append(neighbor)\n if ans==0:\n return 1\n return ans\n``` | 2 | 0 | ['Breadth-First Search', 'Topological Sort', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | C++ | Easy to understand | c-easy-to-understand-by-gourabsingha1-lap2 | \n// start bfs from leaf nodes\n// keep an indegree vector to check leaf node i.e indegree[node] = 1\n// if the leaf nodes value if divisible by k then increase | gourabsingha1 | NORMAL | 2023-09-30T16:01:03.281121+00:00 | 2023-09-30T16:01:03.281152+00:00 | 58 | false | ```\n// start bfs from leaf nodes\n// keep an indegree vector to check leaf node i.e indegree[node] = 1\n// if the leaf nodes value if divisible by k then increase result\n// else pass its value to its parent node\n\nclass Solution {\npublic:\n int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {\n if(edges.size() == 0) return 1;\n int res = 1;\n vector<int> adj[n];\n vector<int> vis(n, 0), indegree(n, 0); // indegree = no. of arrows directed towards\n for (int i = 0; i < edges.size(); i++)\n {\n int u = edges[i][0], v = edges[i][1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n indegree[u]++, indegree[v]++;\n }\n queue<int> q;\n for (int u = 0; u < n; u++)\n {\n if(indegree[u] == 1){\n q.push(u);\n }\n }\n\n while(q.size()) {\n int u = q.front();\n q.pop();\n for(auto& v : adj[u]) {\n if(indegree[v] < 1) continue;\n if(values[u] % k == 0) {\n indegree[u]--, indegree[v]--;\n if(indegree[v] == 1) {\n q.push(v);\n }\n res++;\n break;\n }\n else {\n values[v] += values[u];\n indegree[u]--, indegree[v]--;\n if(indegree[v] == 1) {\n q.push(v);\n }\n }\n }\n }\n return res;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Breadth-First Search', 'Graph'] | 0 |
maximum-number-of-k-divisible-components | Topological Sort Optimal Solution in JAVA,C++ & PYTHON | topological-sort-optimal-solution-in-jav-eivl | Problem Statement:Given a tree with n nodes labeled from 0 to n - 1, and a 2D integer array edges where edges[i] = [ai, bi] indicates an edge between nodes ai a | dipesh1203 | NORMAL | 2024-12-30T12:16:38.808340+00:00 | 2024-12-30T12:16:38.808340+00:00 | 12 | false |
#### Problem Statement:
Given a tree with `n` nodes labeled from `0` to `n - 1`, and a 2D integer array `edges` where `edges[i] = [ai, bi]` indicates an edge between nodes `ai` and `bi`, determine the maximum number of components that can be obtained by removing some edges such that each component's node values sum up to a number divisible by `k`.
---
### Algorithm Explanation:
To solve the problem, we use a topological sorting approach on the tree, leveraging its acyclic property:
1. **Tree Representation**:
- Use an adjacency list to represent the tree.
- Maintain an array `inDeg` to store the in-degrees of nodes.
2. **Initialization**:
- Start with the leaf nodes (nodes with `inDeg[i] == 1`) since they have no dependencies.
- Add them to a queue for processing.
3. **Component Counting**:
- Process each leaf node, checking if its value (or accumulated subtree value) is divisible by `k`. If yes, it contributes to a valid component.
- Propagate the remainder (if not divisible) to its parent node and update the tree structure.
4. **Stop Condition**:
- The process continues until all nodes are processed.
---
### Pseudocode for Topological Sort:
```plaintext
function topologicalSort(tree, values, k):
Initialize queue Q with all leaf nodes (inDeg[i] == 1)
count = 0
newValues = copy of values
while Q is not empty:
curr = Q.remove()
inDeg[curr] -= 1
temp = (newValues[curr] % k == 0) ? 0 : newValues[curr]
if temp == 0:
count += 1
for neighbor in tree[curr]:
if inDeg[neighbor] > 0:
newValues[neighbor] += temp
inDeg[neighbor] -= 1
if inDeg[neighbor] == 1:
Q.add(neighbor)
return count
```
---
### Code Implementation
#### Java:
```java
import java.util.*;
class Solution {
class Edge {
int src, dest;
public Edge(int src, int dest) {
this.src = src;
this.dest = dest;
}
}
public void createGraph(ArrayList<Edge>[] graph, int edges[][], int[] inDeg) {
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(new Edge(edge[0], edge[1]));
graph[edge[1]].add(new Edge(edge[1], edge[0]));
inDeg[edge[0]]++;
inDeg[edge[1]]++;
}
}
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
ArrayList<Edge>[] graph = new ArrayList[n];
int[] inDeg = new int[n];
createGraph(graph, edges, inDeg);
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDeg[i] == 1) q.add(i);
}
int count = 0;
long[] newValues = new long[n];
for (int i = 0; i < n; i++) {
newValues[i] = values[i];
}
while (!q.isEmpty()) {
int curr = q.poll();
inDeg[curr]--;
long temp = (newValues[curr] % k == 0) ? 0 : newValues[curr];
if (temp == 0) count++;
for (Edge e : graph[curr]) {
if (inDeg[e.dest] > 0) {
newValues[e.dest] += temp;
inDeg[e.dest]--;
if (inDeg[e.dest] == 1) {
q.add(e.dest);
}
}
}
}
return count;
}
}
```
---
#### C++:
```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> graph(n);
vector<int> inDeg(n, 0);
for (auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
inDeg[edge[0]]++;
inDeg[edge[1]]++;
}
queue<int> q;
for (int i = 0; i < n; ++i) {
if (inDeg[i] == 1) q.push(i);
}
int count = 0;
vector<long long> newValues(values.begin(), values.end());
while (!q.empty()) {
int curr = q.front(); q.pop();
inDeg[curr]--;
long long temp = (newValues[curr] % k == 0) ? 0 : newValues[curr];
if (temp == 0) count++;
for (int neighbor : graph[curr]) {
if (inDeg[neighbor] > 0) {
newValues[neighbor] += temp;
inDeg[neighbor]--;
if (inDeg[neighbor] == 1) {
q.push(neighbor);
}
}
}
}
return count;
}
};
```
---
#### Python:
```python
from collections import deque, defaultdict
class Solution:
def maxKDivisibleComponents(self, n, edges, values, k):
graph = defaultdict(list)
in_deg = [0] * n
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
in_deg[a] += 1
in_deg[b] += 1
queue = deque([i for i in range(n) if in_deg[i] == 1])
new_values = values[:]
count = 0
while queue:
curr = queue.popleft()
in_deg[curr] -= 1
temp = 0 if new_values[curr] % k == 0 else new_values[curr]
if temp == 0:
count += 1
for neighbor in graph[curr]:
if in_deg[neighbor] > 0:
new_values[neighbor] += temp
in_deg[neighbor] -= 1
if in_deg[neighbor] == 1:
queue.append(neighbor)
return count
```
---
### Complexity Analysis:
1. **Time Complexity**:
- **Graph Construction**: \(O(n)\) as there are \(n - 1\) edges in a tree.
- **Traversal**: \(O(n)\) since every node and edge is processed once.
- **Overall**: \(O(n)\).
2. **Space Complexity**:
- **Adjacency List**: \(O(n)\).
- **Queue**: \(O(n)\) in the worst case.
- **New Values Array**: \(O(n)\).
- **Overall**: \(O(n)\).
---
### Summary:
- This approach efficiently determines the maximum number of components divisible by \(k\) using a topological sort technique.
- The implementation is scalable and works well for large trees due to its \(O(n)\) complexity. | 1 | 0 | ['Tree', 'Depth-First Search', 'Python', 'C++', 'Java', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | ✅ Java Solution | DFS | java-solution-dfs-by-harsh__005-vggv | CODE\nJava []\n// 0 - sum, 1 - number of components\nprivate long[] dfs(int curr, Map<Integer, List<Integer>> map, int[] values, int k, boolean[] vis) {\n\tvis[ | Harsh__005 | NORMAL | 2024-12-21T13:45:03.237864+00:00 | 2024-12-21T13:45:03.237884+00:00 | 62 | false | ## **CODE**\n```Java []\n// 0 - sum, 1 - number of components\nprivate long[] dfs(int curr, Map<Integer, List<Integer>> map, int[] values, int k, boolean[] vis) {\n\tvis[curr] = true;\n\tlong[] ans = new long[2];\n\tans[0] += values[curr];\n\tfor(int child : map.getOrDefault(curr, new ArrayList<>())) {\n\t\tif(vis[child]) continue;\n\t\tlong curr_ans[] = dfs(child, map, values, k, vis);\n\t\tans[0] += curr_ans[0];\n\t\tans[1] += curr_ans[1];\n\t}\n\t\n\tif(ans[0]%k == 0) {\n\t\tans[0] = 0;\n\t\tans[1]++;\n\t}\n\treturn ans;\n}\n\npublic int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {\n\tMap<Integer, List<Integer>> map = new HashMap<>();\n\tfor(int edge[]: edges) {\n\t\tint u = edge[0], v = edge[1];\n\t\tif(!map.containsKey(u)) map.put(u, new ArrayList<>());\n\t\tif(!map.containsKey(v)) map.put(v, new ArrayList<>());\n\t\tmap.get(u).add(v);\n\t\tmap.get(v).add(u);\n\t}\n\treturn (int)dfs(0, map, values, k, new boolean[n])[1];\n}\n``` | 1 | 0 | ['Depth-First Search', 'Java'] | 1 |
maximum-number-of-k-divisible-components | Topological sort + DFS solution | topological-sort-dfs-solution-by-andrewj-qd9p | IntuitionConsider any set of vertex-disjoint k-divisible connected components. Then, any connected component that contains exactly all the edges in those connec | andrewjyuan | NORMAL | 2024-12-21T23:55:32.692786+00:00 | 2024-12-21T23:57:45.134968+00:00 | 9 | false | # Intuition
Consider any set of vertex-disjoint k-divisible connected components. Then, any connected component that contains exactly all the edges in those connected components must also be k-divisible.
# Approach
We proceed with a greedy approach to this solution. Whenever we encounter a smallest possible subtree that is a k-divisible component, we increment the number of possible k-divisible components by 1.
So, we DFS the tree, calculating the sum of the subtrees rooted at each node, and increment our result by 1. This way, it is impossible for any valid split to be "missed" (proving this may be left as an exercise left to the reader).
It's worth noting that it doesn't matter which node we choose as our root for the tree, as the above logic still holds.
# Complexity
Let $$n$$ be the number of nodes in the tree and $$m$$ be the number of edges in the tree.
- Time complexity: $$O(n + m)$$
- Space complexity: $$O(n + m)$$
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(
self, n: int, edges: List[List[int]], values: List[int], k: int
) -> int:
adj = {i: [] for i in range(n)}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
res = 0
visit = set()
def dfs(root):
nonlocal res
visit.add(root)
if not adj[root]:
return values[root]
val_sum = values[root] + sum(
dfs(nei) for nei in adj[root] if nei not in visit
)
if val_sum % k == 0:
res += 1
return val_sum
dfs(0)
return max(res, 1)
``` | 1 | 0 | ['Depth-First Search', 'Topological Sort', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | C# Solution for Maximum Number of K-Divisible Components Problem | c-solution-for-maximum-number-of-k-divis-7qx9 | IntuitionThe problem requires splitting the tree into connected components such that the sum of node values in each component is divisible by k . Since the tre | Aman_Raj_Sinha | NORMAL | 2024-12-21T20:44:44.903892+00:00 | 2024-12-21T20:44:44.903892+00:00 | 13 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires splitting the tree into connected components such that the sum of node values in each component is divisible by k . Since the tree has no cycles, removing an edge always results in two separate components. The goal is to maximize the number of such k -divisible components by strategically removing edges.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Graph Representation:
• Represent the tree as an adjacency list using a Dictionary<int, HashSet<int>>. This allows efficient traversal and edge removal operations.
2. Leaf Node Processing:
• Use a Breadth-First Search (BFS) starting from leaf nodes (nodes with one neighbor).
• Leaf nodes are processed first because they have no dependencies, and their values can directly determine whether they form a valid component.
3. Propagating Values:
• If a node’s value is divisible by k , it can form a valid component, and we increment the component count.
• If not, its value is added to its parent (neighbor) node, effectively propagating the remaining value up the tree.
4. Edge Removal:
• After processing a node, remove the edge between the node and its parent. If the parent becomes a leaf node, it is added to the queue for further processing.
5. End Condition:
• The BFS ends when all nodes have been processed, and the total number of valid k -divisible components is returned.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
1. Graph Construction:
• Building the adjacency list takes O(n) , where n is the number of nodes.
2. BFS Traversal:
• Each node is processed once, and each edge is traversed twice (once for each endpoint). This results in O(n) + O(n - 1) = O(n) .
Total Time Complexity: O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1. Graph Representation:
• The adjacency list uses O(n + n-1) = O(n) space for n nodes and n-1 edges.
2. Queue:
• In the worst case, all leaf nodes are in the queue simultaneously, requiring O(n) space.
3. Value Array:
• An array of size n is used to store the node values, requiring O(n) space.
Total Space Complexity: O(n)
# Code
```csharp []
public class Solution {
public int MaxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
if (n < 2) return 1;
int componentCount = 0;
Dictionary<int, HashSet<int>> graph = new Dictionary<int, HashSet<int>>();
// Step 1: Build the graph
foreach (var edge in edges) {
int node1 = edge[0], node2 = edge[1];
if (!graph.ContainsKey(node1)) graph[node1] = new HashSet<int>();
if (!graph.ContainsKey(node2)) graph[node2] = new HashSet<int>();
graph[node1].Add(node2);
graph[node2].Add(node1);
}
// Convert values to long to prevent overflow
long[] longValues = new long[values.Length];
for (int i = 0; i < values.Length; i++) {
longValues[i] = values[i];
}
// Step 2: Initialize the queue with leaf nodes
Queue<int> queue = new Queue<int>();
foreach (var entry in graph) {
if (entry.Value.Count == 1) {
queue.Enqueue(entry.Key);
}
}
// Step 3: Process nodes in BFS order
while (queue.Count > 0) {
int currentNode = queue.Dequeue();
// Find the neighbor node
int neighborNode = -1;
if (graph[currentNode].Count > 0) {
neighborNode = GetFirstElement(graph[currentNode]);
}
if (neighborNode >= 0) {
// Remove the edge between current and neighbor
graph[neighborNode].Remove(currentNode);
graph[currentNode].Remove(neighborNode);
}
// Check divisibility of the current node's value
if (longValues[currentNode] % k == 0) {
componentCount++;
} else if (neighborNode >= 0) {
// Add current node's value to the neighbor
longValues[neighborNode] += longValues[currentNode];
}
// If the neighbor becomes a leaf node, add it to the queue
if (neighborNode >= 0 && graph[neighborNode].Count == 1) {
queue.Enqueue(neighborNode);
}
}
return componentCount;
}
private int GetFirstElement(HashSet<int> set) {
foreach (var item in set) {
return item;
}
return -1;
}
}
``` | 1 | 0 | ['C#'] | 0 |
maximum-number-of-k-divisible-components | O(N) DFS Python Solution with DP | on-python-solution-by-avendramini-bqr6 | IntuitionThe problem requires splitting a tree into components such that the sum of values in each component is divisible by k. Since a tree is connected and a | avendramini | NORMAL | 2024-12-21T20:42:45.094520+00:00 | 2024-12-21T22:02:18.428568+00:00 | 7 | false | # Intuition
The problem requires splitting a tree into components such that the sum of values in each component is divisible by *k*. Since a tree is connected and acyclic, we can use a DFS traversal to calculate the sum of values for each subtree and determine the maximum number of valid components. By leveraging dynamic programming, we can efficiently track whether a subtree can form valid components.
# Approach
1. **Tree Representation**: Represent the tree using an adjacency list from the given edges.
2. **DFS Traversal**:
- Visit each node and compute the sum of values for its subtree.
- Determine if the subtree can be split into valid components divisible by *k*.
- Use a `dp` structure to memoize intermediate results for each node.
3. **Base Case**:
- For leaf nodes, check if their value is divisible by *k* and initialize the `dp` accordingly.
4. **Result Combination**:
- For each child of a node, update the current sum and the count of valid components.
5. **Final Result**:
- Return the maximum number of valid components from the root node.
# Complexity
- **Time complexity**:
$$O(n)$$, where *n* is the number of nodes, since each node is visited exactly once in the DFS traversal.
- **Space complexity**:
$$ O(n)$$, for the adjacency list, visited array, and the `dp` array.
# Code
```python
class Solution:
def dfs(self, pos, vis, adj, values, k, dp):
vis[pos] = True
leaf = True
# Check if current node is a leaf
for x in adj[pos]:
if not vis[x]:
leaf = False
if leaf:
# If it's a leaf, initialize dp
if values[pos] % k == 0:
dp[pos] = ((values[pos], 0), (0, 1))
else:
dp[pos] = ((values[pos], 0), (0, -1))
return
# Sum and count of partitions
somma = values[pos]
parti = 0
for x in adj[pos]:
if not vis[x]:
self.dfs(x, vis, adj, values, k, dp)
if dp[x][1][1] != -1:
parti += dp[x][1][1]
else:
parti += dp[x][0][1]
somma += dp[x][0][0]
# Update dp based on divisibility by k
if somma % k == 0:
dp[pos] = ((0, parti + 1), (0, parti + 1))
else:
dp[pos] = ((somma, parti), (0, -1))
return
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
# Build adjacency list
adj = [[] for _ in range(n)]
for x in edges:
adj[x[0]].append(x[1])
adj[x[1]].append(x[0])
# Initialize visited array and dp
vis = [False] * n
dp = [()] * n
# Start DFS from node 0
self.dfs(0, vis, adj, values, k, dp)
# Return the maximum number of components
return max(dp[0][1][1], dp[0][0][1])
| 1 | 0 | ['Tree', 'Depth-First Search', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | Java Solution for Maximum Number of K-Divisible Components Problem | java-solution-for-maximum-number-of-k-di-pf7u | IntuitionThe problem asks us to find the maximum number of components in a tree such that the sum of node values in each component is divisible by k. The approa | Aman_Raj_Sinha | NORMAL | 2024-12-21T20:37:47.589360+00:00 | 2024-12-21T20:37:47.589360+00:00 | 12 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem asks us to find the maximum number of components in a tree such that the sum of node values in each component is divisible by k. The approach leverages the properties of trees and their structure:
1. Leaf Nodes and Tree Traversal: Starting from the leaf nodes (nodes with only one connection), we can progressively remove edges and combine values with their neighboring nodes until we process the entire tree.
2. Divisibility Check: For each node processed, if its cumulative value is divisible by k, it forms a valid component, and we increment the component count.
3. Value Propagation: If a node does not form a component, its value is propagated to its parent (neighbor) for further processing.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Graph Construction:
• Represent the tree as an adjacency list (graph) using a HashMap. This allows efficient traversal and edge removal during processing.
2. Initialize BFS Queue:
• Start with all leaf nodes (nodes with only one connection). These are added to a queue for BFS processing.
3. BFS Processing:
• For each node in the queue:
1. Identify its only connected neighbor (parent node).
2. Check if the node’s value is divisible by k:
• If divisible, count it as a valid component and remove it from the graph.
• Otherwise, add its value to the neighbor’s value.
3. Remove the edge between the node and its neighbor.
4. If the neighbor becomes a leaf node after removing the edge, add it to the queue.
4. Return the Component Count:
• After processing all nodes, the count of valid components is returned.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
1. Graph Construction: O(n), where n is the number of nodes. Each edge is added to the graph exactly once.
2. BFS Processing:
• Each node is visited once, and each edge is processed once during removal. This takes O(n + n - 1) = O(n).
3. Total Time Complexity: O(n).
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1. Graph Representation: The adjacency list takes O(n + n - 1) = O(n) space.
2. Queue: The BFS queue stores at most n nodes in the worst case, which takes O(n).
3. Value Array: The longValues array takes O(n) space.
4. Total Space Complexity: O(n).
# Code
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
if (n < 2) return 1;
int componentCount = 0;
Map<Integer, Set<Integer>> graph = new HashMap<>();
// Step 1: Build the graph
for (int[] edge : edges) {
int node1 = edge[0], node2 = edge[1];
graph.computeIfAbsent(node1, key -> new HashSet<>()).add(node2);
graph.computeIfAbsent(node2, key -> new HashSet<>()).add(node1);
}
// Convert values to long to prevent overflow
long[] longValues = new long[values.length];
for (int i = 0; i < values.length; i++) {
longValues[i] = values[i];
}
// Step 2: Initialize the BFS queue with leaf nodes (nodes with only one connection)
Queue<Integer> queue = new LinkedList<>();
for (Map.Entry<Integer, Set<Integer>> entry : graph.entrySet()) {
if (entry.getValue().size() == 1) {
queue.add(entry.getKey());
}
}
// Step 3: Process nodes in BFS order
while (!queue.isEmpty()) {
int currentNode = queue.poll();
// Find the neighbor node
int neighborNode = -1;
if (
graph.get(currentNode) != null &&
!graph.get(currentNode).isEmpty()
) {
neighborNode = graph.get(currentNode).iterator().next();
}
if (neighborNode >= 0) {
// Remove the edge between current and neighbor
graph.get(neighborNode).remove(currentNode);
graph.get(currentNode).remove(neighborNode);
}
// Check divisibility of the current node's value
if (longValues[currentNode] % k == 0) {
componentCount++;
} else if (neighborNode >= 0) {
// Add current node's value to the neighbor
longValues[neighborNode] += longValues[currentNode];
}
// If the neighbor becomes a leaf node, add it to the queue
if (
neighborNode >= 0 &&
graph.get(neighborNode) != null &&
graph.get(neighborNode).size() == 1
) {
queue.add(neighborNode);
}
}
return componentCount;
}
}
``` | 1 | 0 | ['Java'] | 0 |
maximum-number-of-k-divisible-components | Java 17ms runtime, 100% time and 100% space! Detailed Explanation of Maximum Optimizations | java-17ms-runtime-100-time-and-100-space-x3ms | IntuitionThe core idea to the approach is to understand that adding or subtracting multiples of k to some number, will never change the results divisibility by | mshoosterman | NORMAL | 2024-12-21T20:20:35.208855+00:00 | 2024-12-21T20:20:35.208855+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The core idea to the approach is to understand that adding or subtracting multiples of k to some number, will never change the results divisibility by k. This means you can always prune segments which are divisible by k.
This means you should look at leafs first. if their values are divisible by k, then you can prune them and add 1 connected compontent to your result. Otherwise you can add their values to their parents value, and then prune the leaf.
At the and of this step you will have pruned all of the leafs, by either adding their value to their parent, or by disconnecting them from the tree. This means now nodes which used to be parents, will now be leaf nodes, so you can once again look at all leaf nodes. Continuing until there are no nodes left.
This can be done either iteratively, or recusrively. A recursive method may be a bit easier to code, however it is usually less efficient.
# Approach
<!-- Describe your approach to solving the problem. -->
Other than choosing an iterative approach over a recursive approach, all of the optimizations will come from how we chose to represent the tree, and how we transverse it. I.E. how we find leaf and parent nodes.
The comment blocks of the provided code, extensivly explain the optimizations in constructing the tree, so we will gloss over that here, and discuss how to encode the logic for the solution.
We need 2 things, first we need an array, `noConnections` where `noConnections[i]` is the number of nodes connected to the ith node. Leafs will be nodes for which `noConnections[i] == 1`.
We also need a 2D array `tree`, where `tree[i]` is an array consisting of all nodes connected to i.
We will also have 2 Arrayslist, `leafs` and `newLeafs`. And we will add all leaf nodes to `leafs`.
We then can find out solution as follows.
1. create an int called res. this will be our result.
2. Add all leafs to `leafs`.
3. Create a while loop, that runs while `leafs` is not empty.
4. for every node i in `leafs` we check if `vals[i]` is divisible by k.
- if it is divisible by k, then we prune it. we add 1 to res.
- if it is not disivible by k, then we add `vals[i]', to its parents val. Since we dont actually know which node is its parents, we actually add to every node connected to i. This works because every node other than the parent has already been dealt with, and will not be looked at again.
5. We then prune the node, by looking at every node `j` that node `i` is connected to, and subtracting 1 from `noConnections[j]`. If `noConnections[j]` becomes exactly 1, then that means j was the parent of i, and i was its last child, so j is now a leaf. so j can be added to newLeafs.
6. After weve looked at every leaf in `leafs`, we set `leafs = newLeafs` and go through the while loop agian. Once leafs if empty, weve looked at the entire tree, and can return `res`.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Time complexity is $$O(n)$$. in a valid tree the number of connections is always exactly n-1. and each connection will be represented twice in the tree array.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
# Code
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
/*
Later on we will make a basic assumption that every single node is connected
to atleast one other node. This is true in every case, unless n==1. To
benifit from the efficiency of this assumption, we can treat this as a special
case.
*/
if(n == 1){return 1;}
// Construct an array to find the number of Connections each leaf has.
int[] noConnections = new int[n];
for(int[] edge : edges){
noConnections[edge[0]]++;
noConnections[edge[1]]++;
}
// we make a copy of the values array as a long array, to avoid int overflow later on.
long[] vals = new long[n];
for(int i = 0; i<n; i++){vals[i] = values[i];}
/*
We could represent the tree as a hashmap that maps integers to lists.
It is much more efficient however to represent it as a 2D array.
There is no difference in big O runtime or space, however there is a significant
difference in actual runtime, and space.
we create this array in 3 steps.
Step 1:
Initialize a 2d array with n rows, and dont specify the number of columns.
Doing this allows us to have each row have a difference number of columns.
When making an array this way, its important to think about the array, as an array of arrays,
rather than as a matrix.
*/
int[][] tree = new int[n][];
/*
Step 2:
We Initialize each subarray. At every index i, we know that tree[i] should
be an array of all nodes which i connects to. We know that there are
noConnections[i] such nodes. So we set tree[i] to be an array of size noConnections[i].
Then we set the value of tree[i][0] to be its length. We do this to make filling the tree
easier in the 3rd step.
*/
for(int i = 0; i<n; i++){
tree[i] = new int[noConnections[i]];
tree[i][0] = noConnections[i];
}
/*
Step 3:
We fill the 2d array to make it represent the tree.
until tree[i] is completely filled, tree[i][0] tells us where in the array tree[i] we should
place the next value. At the very last step tree[i][0] will be 0, and then it will
overwrite itself. This is a very efficient way of using a 2d Array, but the syntax can
get a bit tricky, so this should be done with care.
*/
for(int[] edge : edges){
int a = edge[0];
int b = edge[1];
tree[a][0]--;
tree[b][0]--;
int index = tree[a][0];
tree[a][index] = b;
index = tree[b][0];
tree[b][index] = a;
}
// We now do a simple breadth first search starting from the leaf nodes.
// After getting to a node, we prune it from its parent.
// once a parrent has all of its children pruned, it becomes a leaf node
// and gets added to newLeafs.
ArrayList<Integer> leafs = new ArrayList<>();
ArrayList<Integer> newLeafs = new ArrayList<>();
int res = 0;
// We start by adding all leaf nodes to leafs arraylist.
for(int i = 0; i<n; i++){
if(noConnections[i] == 1){leafs.add(i);}
}
// we continue adding newly created leafs to the newleafs arraylsit, and then
// switch from looking at leafs to looking at new leafs, untill there are no
// more leafs created, which means we have explored every node.
while(!leafs.isEmpty()){
for(int i : leafs){
if(vals[i] % k == 0){res++;}
else{
for(int j : tree[i]){vals[j] += vals[i];}
}
for(int j : tree[i]){
noConnections[j]--;
if(noConnections[j] == 1){newLeafs.add(j);}
}
}
leafs = newLeafs;
newLeafs = new ArrayList<>();
}
return res;
}
}
``` | 1 | 0 | ['Java'] | 0 |
maximum-number-of-k-divisible-components | DFS Approach || O(n) | dfs-approach-on-by-satwikprem-fifd | IntuitionTo maximize the number of connected components in a tree where each component's sum is divisible by k, we use DFS. By calculating subtree sums, we spli | satwikprem | NORMAL | 2024-12-21T18:40:15.924526+00:00 | 2024-12-21T18:40:15.924526+00:00 | 17 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To maximize the number of connected components in a tree where each component's sum is divisible by `k`, we use DFS. By calculating subtree sums, we split the tree whenever a subtree sum is divisible by `k`.
# Approach
<!-- Describe your approach to solving the problem. -->
1. **Tree Representation:** Use an adjacency list to represent the tree.
2. **DFS Traversal:** Recursively compute subtree sums. Avoid revisiting the parent node to prevent cycles.
3. **Divisibility Check:** If a subtree sum is divisible by k, increment the component count and reset the sum to zero.
4. **Result:** Return the total count of valid components tracked during the traversal.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n) — Each node and edge is visited once.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n) — For adjacency list and recursion stack.
# Code
```java []
class Solution {
public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
// Array of ArrayList for adjacency list
List<Integer>[] adjList = new ArrayList[n];
// Initialize each list
for(int i = 0; i < n; i++){
adjList[i] = new ArrayList<>();
}
for(int[] edge: edges){
int u = edge[0];
int v = edge[1];
// u -> v
adjList[u].add(v);
// v-> u
adjList[v].add(u);
}
int[] components = new int[1];
dfs(0, -1, components, values, k, adjList);
return components[0];
}
long dfs(int currentNode, int parentNode, int[] components,
int[] values, int k, List<Integer>[] adjList){
long sum = values[currentNode];
for(int neighbor : adjList[currentNode]){
if(neighbor != parentNode){
sum += dfs(neighbor, currentNode, components, values, k, adjList);
}
}
if(sum % k == 0){
sum = 0;
components[0]++;
}
return sum;
}
}
```
## 😊Happy Coding!! | 1 | 0 | ['Tree', 'Depth-First Search', 'Java'] | 0 |
maximum-number-of-k-divisible-components | 2872. Maximum Number of K-Divisible Components | 2872-maximum-number-of-k-divisible-compo-ea3a | IntuitionThe problem involves finding the maximum number of components in a tree such that the sum of the node values in each component is divisible by (k). Thi | ayushrawat220804 | NORMAL | 2024-12-21T18:31:15.013836+00:00 | 2024-12-21T18:31:37.713948+00:00 | 23 | false | # Intuition
The problem involves finding the maximum number of components in a tree such that the sum of the node values in each component is divisible by \(k\). This can be achieved using Depth First Search (DFS) to calculate the sum of subtree values and splitting the components whenever a divisible sum is encountered.
# Approach
1. **Represent the Tree**:
- Use an adjacency list to represent the tree.
2. **DFS to Calculate Subtree Sums**:
- Perform a DFS starting from the root node to calculate the sum of values for each subtree.
3. **Split Components**:
- During the DFS traversal, if the sum of values for a subtree is divisible by \(k\), increment the component count and reset the sum for that subtree to 0.
4. **Return the Result**:
- After processing all nodes, return the total number of components.
# Complexity
- **Time Complexity**:
\(O(n)\), where \(n\) is the number of nodes in the tree.
- Each node is visited once during the DFS traversal.
- **Space Complexity**:
\(O(n)\), for storing the adjacency list and recursion stack in the worst case.
# Code
```cpp
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adjList(n); // Adjacency list to represent the tree
// Build the adjacency list from the edges
for (const auto& edge : edges) {
adjList[edge[0]].push_back(edge[1]);
adjList[edge[1]].push_back(edge[0]);
}
int components = 0; // Count of k-divisible components
// Perform DFS to compute subtree sums and count components
dfs(0, -1, adjList, values, k, components);
return components; // Return the total number of components
}
private:
// Helper function for DFS traversal
long dfs(int node, int parent, const vector<vector<int>>& adjList, const vector<int>& values, int k, int& components) {
long sum = values[node]; // Initialize the sum with the value of the current node
// Traverse all neighbors (children) of the current node
for (int neighbor : adjList[node]) {
if (neighbor != parent) { // Avoid revisiting the parent node
// Add the sum from the subtree rooted at the neighbor
sum += dfs(neighbor, node, adjList, values, k, components);
}
}
// Check if the subtree sum is divisible by k
if (sum % k == 0) {
++components; // Increment the component count
return 0; // Reset the sum for this component
}
return sum; // Return the sum to the parent node
}
};
```
# Explanation of Code
1. **Tree Representation**:
- The adjacency list (`adjList`) is created from the given edges to represent the tree.
2. **DFS Function**:
- The `dfs` function calculates the sum of subtree values and checks if the sum is divisible by \(k\).
- If divisible, the subtree forms a separate component, and the sum is reset to 0.
- Otherwise, the sum is passed up to the parent node.
3. **Components Count**:
- The `components` variable is updated whenever a \(k\)-divisible component is encountered.
4. **Return Result**:
- After processing all nodes, the total number of \(k\)-divisible components is returned.
---
##### Hope this helps!! | 1 | 0 | ['C++'] | 0 |
maximum-number-of-k-divisible-components | Best approch to solve step by step with explaination using python | best-approch-to-solve-step-by-step-with-iuqv3 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | abhishekai01 | NORMAL | 2024-12-21T18:10:08.077789+00:00 | 2024-12-21T18:10:08.077789+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution:
def maxKDivisibleComponents(self, n, edges, values, k):
from collections import defaultdict
# Build the adjacency list representation of the tree
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
result = [0]
def dfs(node, parent):
subtree_sum = values[node]
for neighbor in graph[node]:
if neighbor != parent: # Avoid going back to the parent
subtree_sum += dfs(neighbor, node)
if subtree_sum % k == 0:
result[0] += 1
return 0 # Return 0 to mark the subtree as a new component
else:
return subtree_sum
# Start DFS from node 0
dfs(0, -1)
return result[0]
# Example 1
n = 5
edges = [[0, 2], [1, 2], [1, 3], [2, 4]]
values = [1, 8, 1, 4, 4]
k = 6
sol = Solution()
print(sol.maxKDivisibleComponents(n, edges, values, k)) # Output: 2
# Example 2
n = 7
edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [2, 6]]
values = [3, 0, 6, 1, 5, 2, 1]
k = 3
sol = Solution()
print(sol.maxKDivisibleComponents(n, edges, values, k)) # Output: 3
``` | 1 | 0 | ['Python'] | 0 |
maximum-number-of-k-divisible-components | DFS. Simple and clear solution. Runtime 100% | dfs-simple-and-clear-solution-runtime-10-wgxn | null | xxxxkav | NORMAL | 2024-12-21T15:56:59.568559+00:00 | 2024-12-21T15:58:55.841533+00:00 | 23 | false | ```
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
self.ans = 0
def dfs(root, parent):
s = values[root]
for child in graph[root]:
if child != parent:
s += dfs(child, root)
if s%k == 0:
self.ans += 1
return 0
return s
dfs(0, -1)
return self.ans
``` | 1 | 0 | ['Depth-First Search', 'Python3'] | 0 |
maximum-number-of-k-divisible-components | Solution in || Python || | solution-in-python-by-rajatcoder2255-bq4i | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | rajatcoder2255 | NORMAL | 2024-12-21T15:10:04.677659+00:00 | 2024-12-21T15:10:04.677659+00:00 | 17 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
tree = defaultdict(list)
for a, b in edges:
tree[a].append(b)
tree[b].append(a)
visited = set()
self.components = 0
def dfs(node):
visited.add(node)
subtree_sum = values[node]
for neighbor in tree[node]:
if neighbor not in visited:
child_sum = dfs(neighbor)
if child_sum % k == 0:
self.components += 1
else:
subtree_sum += child_sum
return subtree_sum
total_sum = dfs(0)
if total_sum % k == 0:
self.components += 1
return self.components
``` | 1 | 0 | ['Python3'] | 0 |
maximum-number-of-k-divisible-components | C++ Greedy Solution | c-greedy-solution-by-retire-wa1e | Code | Retire | NORMAL | 2024-12-21T14:42:54.878304+00:00 | 2024-12-21T14:42:54.878304+00:00 | 58 | false | # Code
```cpp []
class Solution {
public:
vector<vector<int>> g;
pair<int, int> dfs(int pre, int cur, vector<int> &values, int k) {
pair<int, int> res = {values[cur] % k, 0};
for (auto &x: g[cur]) {
if (x == pre) continue;
auto [cnt, pairs] = dfs(cur, x, values, k);
res.first = (res.first + cnt) % k;
res.second += pairs;
}
if (res.first == 0) res.second += 1;
return res;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
g.resize(n);
for (auto &x: edges) {
g[x[0]].push_back(x[1]);
g[x[1]].push_back(x[0]);
}
return dfs(-1, 0, values, k).second;
}
};
``` | 1 | 0 | ['Greedy', 'C++'] | 0 |
maximum-number-of-k-divisible-components | Easy Solution With C++ | easy-solution-with-c-by-ashraf-abu3lrai-3p95 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Al-Khwarizmi_ | NORMAL | 2024-12-21T14:11:53.511193+00:00 | 2024-12-21T14:11:53.511193+00:00 | 23 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<vector<int>>g;
vector<bool>vis;
int ans=0;
long long dfs(int node,int k,vector<int>& vals)
{
vis[node]=1;
long long sum=vals[node];
for(auto ch:g[node])
{
if(vis[ch]==0){
sum+=dfs(ch,k,vals);
}
}
if(sum%k==0)
{
ans++;
cout<<"a ";
return 0;
}
else return sum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& e, vector<int>& vals, int k) {
g=vector<vector<int>>(n+1);
vis=vector<bool>(n+1);
map<int,int>mp;
for(int i=0;i<e.size();i++)
{
mp[e[i][0]]++;
mp[e[i][1]]++;
g[e[i][0]].push_back(e[i][1]);
g[e[i][1]].push_back(e[i][0]);
}
int node=0;
for(auto [i,j]:mp)if(j==2)node=i;
dfs(node,k,vals);
cout<<node;
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
maximum-number-of-k-divisible-components | C++ 🖥️ | Beats 80% 🏆 | Easy Solution Explained 🧠 | O(n) ⏱️ | Greedy Tree Traversal with Queue 🌳 | c-beats-80-easy-solution-explained-on-gr-v1kx | IntuitionThe task involves splitting a tree into the maximum number of components such that each has a sum divisible by 𝑘. By focusing on leaf nodes first and p | Raza-Jaun | NORMAL | 2024-12-21T13:58:35.538637+00:00 | 2024-12-21T13:59:35.915290+00:00 | 36 | false | # Intuition
The task involves splitting a tree into the maximum number of components such that each has a sum divisible by 𝑘. By focusing on leaf nodes first and propagating their sums to their parent nodes, we simplify the problem iteratively, ensuring an efficient and structured solution.
---
# Approach
Build a graph using an adjacency list and calculate node degrees. Begin with all leaf nodes in a queue and process them iteratively. For each leaf, check if its value is divisible by 𝑘. If not, add its value to its parent. Decrease the degree of neighboring nodes, and enqueue new leaves when their degree becomes 1. Continue until all nodes are processed.
---
# Complexity
- Time complexity:
$$O(n)$$
- Space complexity:
$$O(n)$$
---
# Code
```cpp []
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
if(!edges.size() && n) return n;
vector<int> degrees(n);
vector<vector<int>> graph(n);
for(int i=0; i<edges.size(); i++){
degrees[edges[i][0]]++;
degrees[edges[i][1]]++;
graph[edges[i][0]].push_back(edges[i][1]);
graph[edges[i][1]].push_back(edges[i][0]);
}
queue<int> leafs;
for(int i=0; i<degrees.size(); i++){
if(degrees[i]==1) leafs.push(i);
}
vector<long long> valuesNodes(values.begin(),values.end());
int count = 0;
while(!leafs.empty()){
int frontIndex = leafs.front();
degrees[frontIndex]--;
leafs.pop();
long long sum = 0;
if(!(valuesNodes[frontIndex]%k)) count++;
else sum += valuesNodes[frontIndex];
for(auto neighbour : graph[frontIndex]){
if(!degrees[neighbour]) continue;
degrees[neighbour]--;
valuesNodes[neighbour] += sum;
if(degrees[neighbour]==1) leafs.push(neighbour);
}
}
return count;
}
};
```
---

| 1 | 0 | ['Math', 'Tree', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'Topological Sort', 'Queue', 'Binary Tree', 'Iterator', 'C++'] | 0 |
maximum-number-of-k-divisible-components | A simple solution using DFS | a-simple-solution-using-dfs-by-kumar_van-a8q3 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Kumar_Vanshaj | NORMAL | 2024-12-21T13:39:57.661894+00:00 | 2024-12-21T13:39:57.661894+00:00 | 15 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
// using adjacency list and DFS
var maxKDivisibleComponents = function (n, edges, values, k) {
// adjacency list from edges
const adjList = Array.from({ length: n }, () => []);
for (const [node1, node2] of edges) {
adjList[node1].push(node2);
adjList[node2].push(node1);
}
const componentCount = [0];
const dfs = (currentNode, parentNode) => {
let sum = 0;
for (const neighborNode of adjList[currentNode]) {
if (neighborNode !== parentNode) {
sum += dfs(neighborNode, currentNode);
}
}
sum += values[currentNode];
if (sum % k === 0) {
componentCount[0]++;
sum = 0;
}
return sum;
};
dfs(0, -1);
return componentCount[0];
}
``` | 1 | 0 | ['Linked List', 'Dynamic Programming', 'Greedy', 'Depth-First Search', 'JavaScript'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.