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
minimum-add-to-make-parentheses-valid
[Beats 100%🔥] 2 Solutions Brute & Optimized | Beginner Friendly Explanation🚀
beats-100-2-solutions-brute-optimized-be-yyrc
Solution 1️⃣ :Intuitionwe can track unmatched opening and closing brackets. Key observation:A valid sequence maintains a balance between opening and closing bra
PradhumanGupta
NORMAL
2025-02-22T13:13:34.392540+00:00
2025-02-22T13:13:34.392540+00:00
192
false
# Solution 1️⃣ : # Intuition we can track unmatched opening and closing brackets. - **Key observation:** A valid sequence maintains a balance between opening and closing brackets. - Instead of checking pairs manually, use a **stack** to track unmatched opening brackets. - Every unmatched closing bracket directly contributes to the required additions. # Approach - Use a **stack** to track unmatched `(`. - Traverse the string: - If `(`, push it onto the stack. - If `)`, check if there's a matching `(` in the stack. - If yes, pop `(`. - If no, increment `count` (indicating an unmatched `)`). - The result is the sum of `count` (unmatched `)`) and `stack.size()` (remaining unmatched `(`). # Complexity - **Time Complexity:** $$O(n)$$ (single pass) - **Space Complexity:** $$O(n)$$ (stack usage in worst case) # Code ```java [] class Solution { public int minAddToMakeValid(String s) { Stack<Character> stack = new Stack<>(); int count = 0; // Tracks unmatched closing brackets for (char c : s.toCharArray()) { if (c == '(') { stack.push(c); // Push opening bracket } else { if (stack.isEmpty()) { count++; // No matching '(', so increment unmatched count } else { stack.pop(); // Match found, pop from stack } } } // Remaining unmatched '(' + unmatched ')' return count + stack.size(); } } ``` # Solution 2️⃣: # Intuition To determine the minimum additions needed to make a parentheses string valid, we can use a counter approach instead of a stack. Track unmatched opening and closing brackets separately. # Approach 1. Use two counters: - `l` for unmatched opening brackets `(`. - `r` for unmatched closing brackets `)`. 2. Traverse the string: - If `(` is found, increment `l`. - If `)` is found: - If `l > 0`, decrement `l` (valid pair found). - Else, increment `r` (extra `)` found). 3. The result is `l + r`, representing the unmatched parentheses that need to be added. # Complexity - **Time Complexity:** $$O(n)$$ - **Space Complexity:** $$O(1)$$ ``` Java [] class Solution { public int minAddToMakeValid(String s) { int l = 0; // Tracks unmatched '(' int r = 0; // Tracks unmatched ')' // Iterate through each character in the string for (final char c : s.toCharArray()) { if (c == '(') { ++l; // Increment count of '(' } else { if (l == 0) // If there's no unmatched '(' to pair with ')' ++r; // Count this ')' as unmatched else --l; // Match this ')' with a previous '(' } } return l + r; // Sum of unmatched '(' and ')' } } ``` **Please Upvote⬆️** ![Screenshot 2025-02-15 134751.png](https://assets.leetcode.com/users/images/3c5bb34f-0d5b-41dc-a192-d44fbd6d3072_1740229882.7060237.png)
3
0
['String', 'Stack', 'Greedy', 'Counting', 'Java']
2
minimum-add-to-make-parentheses-valid
Easy to Understand || ✅Beats 100% || C++, Python, Java
easy-to-understand-beats-100-c-python-ja-rcpf
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
anubhav_py
NORMAL
2024-12-22T13:46:37.002797+00:00
2024-12-22T13:46:37.002797+00:00
125
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 ```cpp [] class Solution { public: int minAddToMakeValid(string s) { int count = 0; stack<int> st; for (int i=0; i<s.length(); i++) { if (s[i] == '(') { st.push(i); } else{ if (!st.empty()) { st.pop(); } else{ count += 1; } } } if (!st.empty()){ count += st.size(); } return count; } }; ``` ```python3 [] class Solution: def minAddToMakeValid(self, s: str) -> int: count = 0 stack = [] for i in range(len(s)): if s[i] == "(": stack.append(i) else: if stack: stack.pop() else: count += 1 if stack: count += len(stack) return count ``` ```java [] class Solution { public int minAddToMakeValid(String s) { int count = 0; Stack<Integer> st = new Stack<Integer>(); for (int i=0; i<s.length(); i++) { if (s.charAt(i) == '(') { st.push(i); } else{ if (!st.empty()) { st.pop(); } else{ count++; } } } if (!st.empty()){ count = count + st.size(); } return count; } } ```
3
0
['String', 'Stack', 'C++', 'Java', 'Python3']
0
minimum-add-to-make-parentheses-valid
BEST RECURSIVE CODE, 100% beats
best-recursive-code-100-beats-by-prats22-ldlf
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
Prats22
NORMAL
2024-10-11T05:10:12.618687+00:00
2024-10-11T05:10:12.618717+00:00
27
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```java []\nclass Solution {\n public int minAddToMakeValid(String s) {\n return helper(s, 0, 0, 0); // Pass initial open, close counts, and index\n }\n\n public int helper(String curr, int open, int close, int index) {\n // Base case: if we\'ve checked all characters in the string\n if (index == curr.length()) {\n return open; // At the end, all unmatched open parentheses should be added\n }\n\n int count = 0;\n char c = curr.charAt(index);\n\n if (c == \'(\') {\n count += helper(curr, open + 1, close, index + 1); // Increment open count\n } else {\n if (open > 0) {\n count += helper(curr, open - 1, close, index + 1); // Match with open, reduce open\n } else {\n count += 1 + helper(curr, open, close, index + 1); // No open to match, add one to count\n }\n }\n\n return count;\n }\n}\n\n```
3
0
['Java']
3
minimum-add-to-make-parentheses-valid
C++ , JAVA : SIMPLEAND EASY Approach: Using a Stack to Make Parentheses Valid 🥞
c-java-simpleand-easy-approach-using-a-s-kyut
Intuition \uD83D\uDCA1\nImagine you\'re at a party \uD83C\uDF89 where everyone is wearing either a left or right shoe \uD83D\uDC5E\uD83D\uDC60. Our goal is to m
himanshukansal101
NORMAL
2024-10-09T17:46:09.639024+00:00
2024-10-09T17:46:09.639064+00:00
9
false
# Intuition \uD83D\uDCA1\nImagine you\'re at a party \uD83C\uDF89 where everyone is wearing either a left or right shoe \uD83D\uDC5E\uD83D\uDC60. Our goal is to make sure every left shoe \uD83D\uDC5E has a matching right shoe \uD83D\uDC60. But oh no! Some shoes are unmatched! \uD83D\uDE31\n\nOur job is to count how many lonely shoes are left and how many new shoes \uD83D\uDC5E\uD83D\uDC60 we need to bring in to pair everyone up. In this case, the shoes are parentheses, and we need to make sure every ( has a matching )!\n\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \uD83D\uDEE0\uFE0F\n\n<!-- Describe your approach to solving the problem. -->\n1. We\u2019ll use a stack \uD83E\uDD5E (our magical shoe-closet \uD83E\uDDF3) to keep track of unmatched parentheses:\n- If we see a left parenthesis (, we\u2019ll throw it into the stack \uD83E\uDD5E (like tossing shoes into the closet \uD83E\uDDF3).\n- If we see a right parenthesis ), we\u2019ll check if there\u2019s already a left parenthesis ( waiting for it in the closet:\n- If yes \u2705, we match them and toss the pair away! \uD83D\uDC5E\uD83D\uDC60\n- If no \u274C, we\u2019ll toss the right parenthesis ) into the stack \uD83E\uDD5E as a sad lonely shoe! \uD83D\uDE22\n2. By the end, all that\u2019s left in the stack \uD83E\uDD5E are the lonely unmatched parentheses \uD83D\uDE14. The size of the stack tells us how many new shoes \uD83D\uDC5E\uD83D\uDC60 (parentheses) we need to bring to make things even!\n\n# Complexity \uD83D\uDE80\n\n- Time complexity:\n\nWe only go through the string once \uD83D\uDC40, checking each character and either pushing or popping from the stack \uD83E\uDD5E. So, the time complexity is O(n), where n is the length of the string. \u26A1\n\n- Space complexity:\n\nThe stack can store up to n parentheses \uD83E\uDD5E in the worst case (when every parenthesis is unmatched \uD83D\uDE31), so the space complexity is O(n). \uD83D\uDCE6\n![48b755ae-c41b-474d-966e-aa5674e41ff4_1720943081.9620614.jpeg](https://assets.leetcode.com/users/images/87956ec4-2c78-4493-952f-c9f7e9b24144_1728495951.9930718.jpeg)\n\n# Code \uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB\n\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n\n stack<int>st;\n for(int i=0;i<s.size();i++){\n if(!st.empty() && st.top()==\'(\'){\n if(s[i]==\')\'){\n st.pop();\n }else{\n st.push(s[i]);\n }\n }else{\n st.push(s[i]);\n }\n }\n\n if(st.size()==0){\n return 0;\n }else{\n return st.size();\n }\n }\n};\n```
3
0
['String', 'Stack', 'C++', 'Java']
0
minimum-add-to-make-parentheses-valid
💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100
easiestfaster-lesser-cpython3javacpython-jjw4
Intuition\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n- JavaScript Code -->
Edwards310
NORMAL
2024-10-09T07:44:51.283138+00:00
2024-10-09T07:44:51.283167+00:00
47
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/ce9c3fe0-0c68-4b5f-a7d9-cac6288f1367_1728459471.7489488.jpeg)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416751470?envType=daily-question&envId=2024-10-09\n- ***C++ Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416733400?envType=daily-question&envId=2024-10-09\n- ***Python3 Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416740491?envType=daily-question&envId=2024-10-09\n- ***Java Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416730977?envType=daily-question&envId=2024-10-09\n- ***C Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416742297?envType=daily-question&envId=2024-10-09\n- ***Python Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416738096?envType=daily-question&envId=2024-10-09\n- ***C# Code -->*** https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/submissions/1416749661?envType=daily-question&envId=2024-10-09\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N) //C++ Solution\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1) //C++ Solution\n# Code\n![th.jpeg](https://assets.leetcode.com/users/images/c07ee644-f2d3-4f97-8177-2955227fdb62_1728459878.7931404.jpeg)\n
3
0
['String', 'Stack', 'Greedy', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
1
minimum-add-to-make-parentheses-valid
C++ Solution || O(1) Space and O(n) time || Easy to Understand
c-solution-o1-space-and-on-time-easy-to-pknw7
Intuition\nThe problem requires determining the minimum number of parentheses that need to be added to make a given string of parentheses valid. A valid parenth
Rohit_Raj01
NORMAL
2024-10-09T07:04:27.320371+00:00
2024-10-09T07:04:27.320416+00:00
16
false
# Intuition\nThe problem requires determining the minimum number of parentheses that need to be added to make a given string of parentheses valid. A valid parentheses string has balanced open and close parentheses. If we encounter a closing parenthesis without a matching opening one, we need to add an opening parenthesis. Similarly, if there are more opening parentheses left unmatched, we need to add closing parentheses.\n\n# Approach\n- `size`: the current balance of unmatched opening parentheses. It is incremented when encountering an opening parenthesis `(`.\n- `cnt`: the number of unmatched closing parentheses `)`. It is incremented when a closing parenthesis is encountered and there are no unmatched opening parentheses to pair with it.\n\n1. For each character in the string:\n - If the character is an opening parenthesis `(`, increase the `size` (unmatched opening parentheses).\n - If the character is a closing parenthesis `)`:\n - If there are unmatched opening parentheses (`size > 0`), decrease the size by 1, as the closing parenthesis can balance an opening one.\n - If no unmatched opening parentheses are available (`size == 0`), increment the `cnt` (count of unmatched closing parentheses).\n2. At the end of the loop:\n - `cnt` holds the number of unmatched closing parentheses.\n - `size` holds the number of unmatched opening parentheses.\n3. The total number of parentheses that need to be added to make the string valid is the sum of `cnt` and `size`.\n\n# Complexity\n- Time complexity: $$O(n)$$ \n\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int size = 0;\n int cnt = 0;\n for (auto& ch : s) {\n if (ch == \'(\') {\n size++;\n } else {\n if (size == 0)\n cnt++;\n else\n size--;\n }\n }\n return cnt + size;\n }\n};\n```\n\n> ***Success is not final, failure is not fatal: It is the courage to continue that counts.***\n\n![1721315779911.jpeg](https://assets.leetcode.com/users/images/7ef4dc4e-7b1d-49e7-95bb-84cc3e885721_1728457436.8190918.jpeg)\n
3
0
['String', 'C++']
1
minimum-add-to-make-parentheses-valid
C++// Beats 100% - easy approach
c-beats-100-easy-approach-by-yashrawat7-qwur
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst thought was to keep a count of open bracket and close brackets. The differece wou
Yashrawat7
NORMAL
2024-10-09T06:18:41.631859+00:00
2024-10-09T06:18:41.631897+00:00
22
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst thought was to keep a count of open bracket and close brackets. The differece would be the moves we need, but it would fail for a testcase like: \') ) ) ( ( (\'.\n\nHence, we need to make a move at each point when the string becomes unbalanced. \nIn the end, we also need to add the number of extra open parentheses in the moves.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Maintain 3 variables: open, close, move.\n- Iterate over the string and keep the count of open and close brackets.\n- If at any iteration the number of close brackets is more than open brackets increment the move. Also increment open, as if we added an open bracket at that index to balance the string up until that point.\n- After we have iterated the whole string we add the difference of open and close bracket in moves. This is for the open brackets that appear at the end of the string. Ex. "( ) ) ) ( (".\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int i = 0, n = s.length();\n int open = 0, close = 0, move = 0;\n for(int i = 0;i<n;i++){\n if(s[i] == \'(\') open++;\n else if(s[i] == \')\') close++;\n if(close>open){\n move++;\n open++;\n } \n }\n move+= open - close;\n return move;\n }\n};\n```
3
0
['C++']
2
minimum-add-to-make-parentheses-valid
🔥✅ Java | 100% faster | easy looping solution 🔥✅
java-100-faster-easy-looping-solution-by-7ixc
Intuition\nIt\'s about balancing parentheses. Whenever a closing parenthesis is encountered, it should be balanced; otherwise, insert an opening parenthesis bef
Surendaar
NORMAL
2024-10-09T04:22:15.091326+00:00
2024-10-09T04:22:15.091352+00:00
123
false
# Intuition\nIt\'s about balancing parentheses. Whenever a closing parenthesis is encountered, it should be balanced; otherwise, insert an opening parenthesis before it. At the end, if there are any unclosed opening parentheses, close all of them.\n\n# Approach\n1. Keep a variable bracket to keep track of the number of opening and closing paranthesis\n2. Iterate through the loop and see if bracket is less than zero which is unbalanced and add the result\n3. Add the excess open brackets which are not closed to result and return it.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minAddToMakeValid(String s) {\n int bracket = 0,len = s.length(), res=0;\n for(int i=0; i<len; i++){\n if(s.charAt(i)==\'(\'){\n bracket++;\n } else{\n bracket--;\n }\n if(bracket<0){\n res++;\n bracket++;\n }\n }\n return res+bracket;\n }\n}\n```
3
0
['Greedy', 'Java']
1
minimum-add-to-make-parentheses-valid
"🔗 Stack Magic: Minimum Add to Balance Parentheses ⚖️"
stack-magic-minimum-add-to-balance-paren-8ech
\uD83E\uDDE0 Intuition:\n1. "Balancing Parentheses" \uD83E\uDDE9:\n For every (, we need a matching ).\n If they don\u2019t match, we need to either remove
sajidmujawar
NORMAL
2024-10-09T04:10:35.407719+00:00
2024-10-09T04:11:19.406994+00:00
10
false
# \uD83E\uDDE0 Intuition:\n1. "Balancing Parentheses" \uD83E\uDDE9:\n <ul><li>For every (, we need a matching ).</li>\n <li>If they don\u2019t match, we need to either remove extra parentheses or add some.</li></ul>\n\n2. Use a Stack \uD83D\uDDC4\uFE0F:\n <ul><li>\n The stack helps us keep track of unmatched parentheses.</li>\n <li>Push ( when you find one.</li>\n <li>Pop ( when you find a matching ).</li></ul>\n\n3. Unmatched Parentheses \uD83C\uDFAF:\n <ul><li>At the end, whatever is left in the stack is the number of unmatched parentheses, which equals how many we need to add to make the string valid.</li>\n</ul>\n\n# \uD83D\uDCA1 Approach:\n1. Start with an empty stack \uD83C\uDD95:\n <ul><li>stack = ""</li></ul>\n\n2. Traverse the string s \uD83D\uDEB6:\n<ul>\n<li><ul>For each character:\n<li>If the top of the stack is ( and the current character is ), pop the stack (since it\'s a valid pair) \u2796.</li>\n<li>Otherwise, push the current character onto the stack \u2795.</li></ul></li></ul>\n\n3. Final Count \uD83D\uDCCF:\n <ul><li>The size of the stack at the end gives the number of unmatched parentheses. Return this value.</li><ul>\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n $$O(n)$$\n\n# \uD83D\uDDBC\uFE0F Image Visualization (Stack Operation):\n\n\n ```\ns = "())("\n\n Initial Stack: ""\n Step 1: "(" -> Push -> Stack: "("\n Step 2: ")" -> Pop -> Stack: ""\n Step 3: ")" -> Push -> Stack: ")"\n Step 4: "(" -> Push -> Stack: ")("\n \n Final Stack: ")("\n Unmatched count = 2\n```\n![hfZf8Yf.png](https://assets.leetcode.com/users/images/a0fc08b2-f290-48ae-a0b8-f834aff06689_1728446958.7389562.png)\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n string stack="";\n for(int i=0;i<s.size();i++)\n {\n if(stack.size() && stack.back()==\'(\' && s[i]==\')\')\n stack.pop_back();\n else\n stack.push_back(s[i]);\n }\n\n return stack.size();\n }\n};\n```
3
0
['String', 'Stack', 'C++']
0
minimum-add-to-make-parentheses-valid
Beats 100% || O(1) space || C++ || Greedy
beats-100-o1-space-c-greedy-by-akash92-lhsz
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen dealing with valid parentheses, every opening parenthesis ( must have a correspond
akash92
NORMAL
2024-10-09T04:05:29.345839+00:00
2024-10-09T04:05:29.345875+00:00
23
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen dealing with valid parentheses, every opening parenthesis ( must have a corresponding closing parenthesis ). Our task is to count how many parentheses need to be added to make the string valid. This boils down to counting unmatched opening or closing parentheses as we traverse the string.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe traverse the string from left to right, keeping track of two counters:\n\n1.\topen: Counts unmatched opening parentheses (.\n2.\tclose: Counts unmatched closing parentheses ).\n\nFor each character in the string:\n\n\u2022\tIf it\u2019s an opening parenthesis (, we increment the open counter.\n\u2022\tIf it\u2019s a closing parenthesis ), we first check if there are any unmatched opening parentheses (open > 0). If there are, we pair the closing parenthesis with an unmatched opening parenthesis (decrement open). If not, we increment the close counter since this closing parenthesis is unmatched.\n\nAt the end, the total number of parentheses to add is the sum of unmatched opening parentheses (open) and unmatched closing parentheses (close).\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int open = 0, close = 0;\n for(auto it: s){\n if(it == \'(\') ++open;\n else{\n if(open > 0) --open;\n else ++close;\n }\n }\n return open + close;\n }\n};\nauto speedup = [](){ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0;}();\n```
3
0
['String', 'Greedy', 'C++']
0
minimum-add-to-make-parentheses-valid
simple and easy Python solution || O(n) || O(1)
simple-and-easy-python-solution-on-o1-by-htf0
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n\n# Complexity\n- Time complexi
shishirRsiam
NORMAL
2024-10-09T03:27:18.467563+00:00
2024-10-09T03:27:18.467596+00:00
343
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n count, ans = 0, 0\n\n for ch in s:\n if ch ==\'(\': count += 1\n elif count: count -= 1\n else: ans += 1\n return ans + count\n```
3
0
['String', 'Stack', 'Greedy', 'Python', 'Python3']
8
minimum-add-to-make-parentheses-valid
✅100% Beats simple solution✅
100-beats-simple-solution-by-binoy_saren-qa5z
Intuition\n Describe your first thoughts on how to solve this problem. \nThe idea is to keep a balance between open and close parentheses while iterating throug
binoy_saren
NORMAL
2024-10-09T03:23:10.518157+00:00
2024-10-09T03:23:10.518185+00:00
88
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to keep a balance between open and close parentheses while iterating through the string. If there are more close parentheses than open ones at any point, you should track the extra close parentheses needed. At the end, the remaining unmatched open parentheses should be counted as well.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Traverse the string and track unmatched open (() and close ()) parentheses.\n \n2. For each (, increment the count of open parentheses.\n\n3. For each ), if there are unmatched open parentheses, decrement the open count; otherwise, increment the count of unmatched close parentheses.\n\n4. The final result is the sum of unmatched open and close parentheses, which gives the minimum additions needed to make the string valid.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n```c++ []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int open = 0, close = 0;\n for (char c : s) {\n if (c == \'(\') {\n open++;\n } else {\n if (open > 0) {\n open--;\n } else {\n close++;\n }\n }\n }\n return open + close;\n }\n};\n\n```\n```python []\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n open = close = 0\n for c in s:\n if c == \'(\':\n open += 1\n else:\n if open > 0:\n open -= 1\n else:\n close += 1\n return open + close\n\n```\n```java []\nclass Solution {\n public int minAddToMakeValid(String s) {\n int open=0;\n int close=0;\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'(\'){\n open++;\n }\n else if(s.charAt(i)==\')\'){\n if (open > 0) {\n open--; \n } else {\n close++; \n }\n }\n } \n return open+close;\n }\n}\n```
3
0
['String', 'Python', 'C++', 'Java']
1
minimum-add-to-make-parentheses-valid
simple and easy C++ solution || O(n) || O(1)
simple-and-easy-c-solution-on-o1-by-shis-90da
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n\n# Complexity\n- Time complexi
shishirRsiam
NORMAL
2024-10-09T03:22:16.592459+00:00
2024-10-09T03:22:16.592493+00:00
156
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) \n {\n int count = 0, ans = 0;\n\n for(auto ch : s)\n {\n if(ch == \'(\') count++;\n else count ? count -- : ans++;\n }\n\n return ans + count;\n }\n};\n```
3
0
['String', 'Stack', 'Greedy', 'C++']
7
minimum-add-to-make-parentheses-valid
Effcient Aproach || 0 ms || C++ || Minimum Add to Make Parentheses Valid
effcient-aproach-0-ms-c-minimum-add-to-m-i9fh
Intuition\n Describe your first thoughts on how to solve this problem. \nHere, for every opening parentheses \'(\', there should be corresponding closing bracke
Shuklajii109
NORMAL
2024-10-09T03:08:05.299826+00:00
2024-10-09T03:08:05.299870+00:00
35
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere, for every opening parentheses \'(\', there should be corresponding closing bracket \')\' to make a string valid. We, iterate the string from start to end then the closing parenthesis should not exceed the opening parenthesis.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. To make string valid, we intialize variable ans and count as 0. \n2. Here, ans is a total no. of moves and count will track the opening & closing braces as we iterate.\n3. If size is 0 then return 0 only.\n4. We iterate a string from left to right, if s[i] is a opening parenthese, increment the ans.\n5. else, If s[i] is a closing parenthese, decrement the ans.\n6. If, ans < 0, then increment count and set ans as 0.\n7. At last, return sum of count and ans.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int n = s.size();\n\n int ans = 0;\n int count = 0;\n\n if(n == 0)\n {\n return 0;\n }\n\n for(int i=0; i<n; i++)\n {\n if(s[i] == \'(\')\n {\n ans++;\n }\n else if(s[i] == \')\')\n {\n ans--;\n }\n\n if(ans < 0)\n {\n count++;\n ans = 0;\n\n }\n }\n\n return count + ans;\n }\n};\n```
3
0
['String', 'Stack', 'Greedy', 'C++']
2
minimum-add-to-make-parentheses-valid
✅Beats 100% | GREEDY | JAVA | Explained🔥🔥🔥
beats-100-greedy-java-explained-by-adnan-cwll
Approach:\nWe can iterate through the string and track the unmatched parentheses. \nSpecifically, we\'ll count:\n\nUnmatched opening brackets: These are ( for w
AdnanNShaikh
NORMAL
2024-10-09T01:08:50.280882+00:00
2024-10-09T01:08:50.280912+00:00
117
false
**Approach:**\nWe can iterate through the string and track the unmatched parentheses. \nSpecifically, we\'ll count:\n\n**Unmatched opening brackets:** These are ( for which we haven\'t yet found a matching ).\n**Unmatched closing brackets:** These are ) that don\'t have an opening bracket ( before them.\n\n**Plan:**\n\n**We use two variables:**\nopen_needed: Keeps track of how many opening parentheses we need to match closing parentheses.\nclose_needed: Keeps track of how many closing parentheses we need.\n\n**Traverse the string:**\nIf we encounter (, it means we will need a closing parenthesis later, so we increase the close_needed count.\n\n**If we encounter ):**\nIf there\'s a corresponding opening ( (i.e., close_needed > 0), we decrease the close_needed.\nIf not (i.e., close_needed == 0), we need an additional opening ( to match this closing bracket, so we increase open_needed.\nAt the end of the traversal, the total number of moves will be the sum of open_needed (missing opening brackets) and close_needed (missing closing brackets).\n\n**Time Complexity:**\nThe time complexity is O(n) where n is the length of the string, as we process each character once.\n\n**Space Complexity:**\nThe space complexity is O(1) as we only use a few integer variables to track the counts.\nThis approach efficiently calculates the minimum number of moves to make the string valid.\n# Code\n```java []\nclass Solution {\n public int minAddToMakeValid(String s) {\n int open_needed = 0; // To track unmatched opening \'(\'\n int close_needed = 0; // To track unmatched closing \')\'\n \n for (char c : s.toCharArray()) {\n if (c == \'(\') {\n close_needed++; // We need a closing \')\' for every \'(\'\n } else if (c == \')\') {\n if (close_needed > 0) {\n close_needed--; // Found a matching \'(\' for the \')\'\n } else {\n open_needed++; // We need an extra \'(\' to match this \')\'\n }\n }\n }\n return open_needed + close_needed;\n }\n}\n```
3
0
['Java']
1
minimum-add-to-make-parentheses-valid
Detailed explanation - O(n) | O(1) - Python, C++
detailed-explanation-on-o1-python-c-by-m-7oyc
Intuition\nLet the level at position i be the number of opening parentheses ( minus number of closing parentheses ) in prefix up to i-th char inclusively. The s
makcymal
NORMAL
2024-10-09T00:44:30.801908+00:00
2024-10-09T00:44:30.801939+00:00
95
false
# Intuition\nLet the level at position `i` be the number of opening parentheses `(` minus number of closing parentheses `)` in prefix up to `i`-th char inclusively. The string is invalid if and only if this level falls below zero somewhere or it\'s not zero at the end of the string.\n\n# Approach\nIf we encounter the position where the level is below zero we can raise the level on the whole string by adding some opening parentheses at the very beginning of the string. Say we have string `str`:\n\n```\npos: 0 1 2 3 4 5 6 7\nstr: ( ( ) ) ) ( ) )\nlvl: 0 1 2 1 0 -1 0 -1 -2\n```\n\nHow many parentheses we should add at the beginning of the string? We want to avoid falling level below zero on the positions 4, 6, 7 and on posisition 7 the level reaches it\'s minimum -2. So we want to add exactly 2 opening parentheses:\n\n```\npos: 0 1 2 3 4 5 6 7\nstr: ( ( ( ( ) ) ) ( ) )\nlvl: 0 1 2 3 4 3 2 1 2 1 0\n``` \n\nThe second case of string invalidation is when the parentheses sequence isn\'t closed properly. Look at another example `str`:\n\n```\npos: 0 1 2 3 4 5\nstr: ( ) ) ) ( (\nlvl: 0 1 0 -1 -2 -1 0\n```\n\nFirst, we don\'t want level to fall below zero so we add two `(`:\n\n```\npos: 0 1 2 3 4 5 6 7\nstr: ( ( ( ) ) ) ( (\nlvl: 0 1 2 3 2 1 0 1 2\n```\n\nAnd now we see clearly we should add two `)` at the end to make parenthese close:\n\n```\npos: 0 1 2 3 4 5 6 7 8 9\nstr: ( ( ( ) ) ) ( ( ) )\nlvl: 0 1 2 3 2 1 0 1 2 1 0\n```\n\n# Algorithm\n\n1. Find minimum level `min_lvl`. Initially `min_lvl = lvl = 0`;\n2. Raise the level at the whole string by adding `-min_lvl` opening parentheses at the beginning. If it\'s zero it\'s zero);\n3. Look at the level at the end: we raise it by `-min_lvl` and now `lvl >= 0` but we should make `lvl = 0`. To do so we add `lvl` closing paretheses at the end.\n4. Total number of added parentheses is `-min_lvl + (lvl + -min_lvl)`\n\n# Complexity\n- Time complexity:\n$O(n)$ \n- Space complexity:\n$O(1)$\n\n# Code\n```python3 []\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n lvl = 0\n min_lvl = 0\n for c in s:\n if c == \'(\':\n lvl += 1\n else:\n lvl -= 1\n min_lvl = min(min_lvl, lvl)\n moves = 0\n if min_lvl < 0:\n lvl += -min_lvl\n moves += -min_lvl\n return moves + lvl\n\n```\n\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int lvl = 0, min_lvl = 0;\n for (char c: s) {\n if (c == \'(\') {\n lvl++;\n } else {\n lvl--;\n min_lvl = min(min_lvl, lvl);\n }\n }\n int moves = 0;\n if (min_lvl < 0) {\n lvl += -min_lvl;\n moves += -min_lvl;\n }\n return moves + lvl;\n }\n};\n```
3
0
['String', 'C++', 'Python3']
1
minimum-add-to-make-parentheses-valid
✅ Beats 100% | Working 08.10.2024 | Explained step by step
beats-100-working-08102024-explained-ste-8hr6
python3 []\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n # Initialize the counter for minimum additions needed\n ans = 0\n
Piotr_Maminski
NORMAL
2024-10-09T00:32:22.080979+00:00
2024-10-09T00:55:31.552323+00:00
288
false
```python3 []\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n # Initialize the counter for minimum additions needed\n ans = 0\n \n # Initialize the balance of parentheses (open - close)\n bal = 0\n\n # Iterate through each character in the string\n for ch in s:\n if ch == \'(\':\n # If it\'s an opening parenthesis, increment the balance\n bal += 1\n else:\n # If it\'s a closing parenthesis, decrement the balance\n bal -= 1\n\n # If balance becomes negative (more closing than opening parentheses)\n if bal < 0:\n # Add the absolute value of balance to answer\n # This represents the number of opening parentheses we need to add\n ans += -bal\n # Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0\n\n # After processing all characters, add any remaining open parentheses\n # This represents the number of closing parentheses we need to add\n ans += bal\n\n # Return the minimum number of additions needed to make the string valid\n return ans\n```\n```cpp []\n#include <string>\n\nclass Solution {\npublic:\n int minAddToMakeValid(std::string s) {\n // \'need\' represents the number of closing parentheses \')\' needed\n // to balance the opening parentheses \'(\'\n int need = 0;\n\n // \'res\' keeps track of the minimum number of parentheses\n // that need to be added to make the string valid\n int res = 0;\n\n // Iterate through each character in the input string\n for (char p : s) {\n if (p == \'(\') {\n // If we encounter an opening parenthesis,\n // we increase the need for a closing parenthesis\n need++;\n }\n \n if (p == \')\') {\n // If we encounter a closing parenthesis,\n // we decrease the need (as it matches an opening parenthesis)\n need--;\n\n // If \'need\' becomes -1, it means we have an extra closing parenthesis\n // that doesn\'t match any opening parenthesis\n if (need == -1) {\n // We need to add an opening parenthesis to balance this\n res++;\n // Reset \'need\' to 0 as we\'ve handled this imbalance\n need = 0;\n }\n }\n }\n\n // The final result is the sum of:\n // 1. \'res\': the number of parentheses we needed to add for balancing extra closing parentheses\n // 2. \'need\': the number of closing parentheses we still need to add to balance remaining opening parentheses\n return res + need;\n }\n};\n```\n```java []\nclass Solution {\n public int minAddToMakeValid(String s) {\n // Initialize the counter for minimum additions needed\n int ans = 0;\n \n // Initialize the balance of parentheses (open - close)\n int bal = 0;\n \n // Iterate through each character in the string\n for (char ch : s.toCharArray()) {\n if (ch == \'(\') {\n // If it\'s an opening parenthesis, increment the balance\n bal++;\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal--;\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if (bal < 0) {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal;\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0;\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal;\n \n // Return the minimum number of additions needed to make the string valid\n return ans;\n }\n}\n```\n```golang []\npackage main\n\nfunc minAddToMakeValid(s string) int {\n // Initialize the counter for minimum additions needed\n ans := 0\n \n // Initialize the balance of parentheses (open - close)\n bal := 0\n \n // Iterate through each character in the string\n for _, ch := range s {\n if ch == \'(\' {\n // If it\'s an opening parenthesis, increment the balance\n bal++\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal--\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if bal < 0 {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal\n \n // Return the minimum number of additions needed to make the string valid\n return ans\n}\n```\n```javascript [JS]\n/**\n * @param {string} s\n * @return {number}\n */\nvar minAddToMakeValid = function(s) {\n // Initialize the counter for minimum additions needed\n let ans = 0;\n \n // Initialize the balance of parentheses (open - close)\n let bal = 0;\n \n // Iterate through each character in the string\n for (let ch of s) {\n if (ch === \'(\') {\n // If it\'s an opening parenthesis, increment the balance\n bal++;\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal--;\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if (bal < 0) {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal;\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0;\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal;\n \n // Return the minimum number of additions needed to make the string valid\n return ans;\n};\n```\n```typescript [TS]\nfunction minAddToMakeValid(s: string): number {\n // Initialize the counter for minimum additions needed\n let ans: number = 0;\n \n // Initialize the balance of parentheses (open - close)\n let bal: number = 0;\n \n // Iterate through each character in the string\n for (let ch of s) {\n if (ch === \'(\') {\n // If it\'s an opening parenthesis, increment the balance\n bal++;\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal--;\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if (bal < 0) {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal;\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0;\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal;\n \n // Return the minimum number of additions needed to make the string valid\n return ans;\n}\n```\n```csharp []\npublic class Solution {\n public int MinAddToMakeValid(string s) {\n // Initialize the counter for minimum additions needed\n int ans = 0;\n \n // Initialize the balance of parentheses (open - close)\n int bal = 0;\n \n // Iterate through each character in the string\n foreach (char ch in s) {\n if (ch == \'(\') {\n // If it\'s an opening parenthesis, increment the balance\n bal++;\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal--;\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if (bal < 0) {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal;\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0;\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal;\n \n // Return the minimum number of additions needed to make the string valid\n return ans;\n }\n}\n```\n```ruby []\n# @param {String} s\n# @return {Integer}\ndef min_add_to_make_valid(s)\n # Initialize the counter for minimum additions needed\n ans = 0\n \n # Initialize the balance of parentheses (open - close)\n bal = 0\n \n # Iterate through each character in the string\n s.each_char do |ch|\n if ch == \'(\'\n # If it\'s an opening parenthesis, increment the balance\n bal += 1\n else\n # If it\'s a closing parenthesis, decrement the balance\n bal -= 1\n end\n \n # If balance becomes negative (more closing than opening parentheses)\n if bal < 0\n # Add the absolute value of balance to answer\n # This represents the number of opening parentheses we need to add\n ans += -bal\n # Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0\n end\n end\n \n # After processing all characters, add any remaining open parentheses\n # This represents the number of closing parentheses we need to add\n ans += bal\n \n # Return the minimum number of additions needed to make the string valid\n ans\nend\n```\n```rust []\nimpl Solution {\n pub fn min_add_to_make_valid(s: String) -> i32 {\n // Initialize the counter for minimum additions needed\n let mut ans = 0;\n \n // Initialize the balance of parentheses (open - close)\n let mut bal = 0;\n \n // Iterate through each character in the string\n for ch in s.chars() {\n if ch == \'(\' {\n // If it\'s an opening parenthesis, increment the balance\n bal += 1;\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal -= 1;\n }\n \n // If balance becomes negative (more closing than opening parentheses)\n if bal < 0 {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal;\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0;\n }\n }\n \n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal;\n \n // Return the minimum number of additions needed to make the string valid\n ans\n }\n}\n```\n```swift []\nclass Solution {\n func minAddToMakeValid(_ s: String) -> Int {\n // Initialize the counter for minimum additions needed\n var ans = 0\n \n // Initialize the balance of parentheses (open - close)\n var bal = 0\n\n // Iterate through each character in the string\n for ch in s {\n if ch == "(" {\n // If it\'s an opening parenthesis, increment the balance\n bal += 1\n } else {\n // If it\'s a closing parenthesis, decrement the balance\n bal -= 1\n }\n\n // If balance becomes negative (more closing than opening parentheses)\n if bal < 0 {\n // Add the absolute value of balance to answer\n // This represents the number of opening parentheses we need to add\n ans += -bal\n // Reset balance to 0 since we\'ve accounted for the imbalance\n bal = 0\n }\n }\n\n // After processing all characters, add any remaining open parentheses\n // This represents the number of closing parentheses we need to add\n ans += bal\n\n // Return the minimum number of additions needed to make the string valid\n return ans\n }\n}\n```\n### Complexity (python as example)\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n## Explained step by step\n1. We start with a class called `Solution` that has a method `minAddToMakeValid`. This method takes a string `s` as input and returns an integer.\n2. We create a variable `ans` and set it to **0**. This will keep track of how many parentheses we need to add.\n3. We create another variable `bal` and set it to **0**. This will keep track of the balance between opening and closing parentheses.\n4. We then go through each character in the input string `s`:\n- a. If the character is an opening parenthesis \'(\', we increase `bal` by **1**.\n- b. If it\'s a closing parenthesis \')\', we decrease **bal** by **1**.\n5. After each character, we check if `bal` has become negative. If it has:\n- We add the absolute value of `bal` to ans. This is because a negative balance means we have more closing parentheses than opening ones, so we need to add some opening ones.\n- We then reset `bal` to **0** since we\'ve fixed the imbalance.\n6. After we\'ve gone through all the characters, we add the final value of `bal` to `ans`. This is because if `bal` is positive, it means we have more opening parentheses than closing ones, so we need to add some closing ones.\n7. Finally, we return `ans`, which represents the total number of parentheses we needed to add to make the string valid.\n\nIn essence, this method counts how many parentheses we need to add to make sure every opening parenthesis has a matching closing parenthesis, and vice versa.\n\n![image.png](https://assets.leetcode.com/users/images/410e442d-cd4d-4898-8491-d73274757cac_1728433680.8203661.png)\n\n![image.png](https://assets.leetcode.com/users/images/57926bd5-e4e7-4586-855c-6b561a48182f_1728433656.3987143.png)\n\n\n\n![image.png](https://assets.leetcode.com/users/images/9dc1b265-b175-4bf4-bc6c-4b188cb79220_1728176037.4402142.png)\n\n
3
0
['Swift', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']
1
minimum-add-to-make-parentheses-valid
Beats 100%, simple easy to understand, and beginner-friendly using stack
beats-100-simple-easy-to-understand-and-m7haj
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\ncpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n s
navendupandey_14
NORMAL
2024-08-27T11:54:20.214797+00:00
2024-08-27T11:54:20.214840+00:00
6
false
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char> st; // Stack to keep track of unmatched \'(\' characters\n int n = s.size(); // Length of the input string\n int count = 0; // Counter for unmatched \')\' characters\n\n // Loop through each character in the string\n for (int i = 0; i < n; i++) {\n if (s[i] == \'(\') { \n st.push(s[i]); // Push \'(\' onto the stack to track unmatched \'(\'\n } else if (s[i] == \')\') { // When encountering a \')\'\n if (!st.empty() && st.top() == \'(\') {\n st.pop(); // If there\'s a matching \'(\', pop it from the stack\n } else {\n count++; // If there\'s no matching \'(\', increment the count of unmatched \')\'\n }\n }\n }\n\n // Add the remaining unmatched \'(\' in the stack to the count\n count += st.size();\n\n return count; // Return the total number of insertions needed\n }\n};\n```
3
0
['String', 'Stack', 'Greedy', 'C++']
0
minimum-add-to-make-parentheses-valid
Easy Solution in C++
easy-solution-in-c-by-abdkhaleel-k9a8
\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n
abdkhaleel
NORMAL
2024-06-16T14:59:03.895393+00:00
2024-06-16T14:59:03.895426+00:00
315
false
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n\n int lwait = 0;\n int rwait = 0;\n for(char c : s){\n if(c == \')\'){\n rwait++;\n if(lwait > 0) {\n rwait = rwait - 1;\n lwait--;\n }\n continue;\n }\n lwait++;\n }\n return lwait+rwait;\n\n \n }\n};\n```
3
0
['C++']
1
minimum-add-to-make-parentheses-valid
Easiest Solution || Beginner Level || C++
easiest-solution-beginner-level-c-by-san-f8bu
\n# Code\nC++\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int n=s.length();\n stack<int> st;\n for(int i=0;i<n;i++)
sanon2025
NORMAL
2024-05-14T16:23:09.867752+00:00
2024-05-14T16:23:09.867782+00:00
523
false
\n# Code\n```C++\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int n=s.length();\n stack<int> st;\n for(int i=0;i<n;i++){\n char c=s[i];\n if(!st.empty()&&(st.top()==\'(\'&&c==\')\')){\n st.pop();\n } else{\n st.push(c);\n }\n }\n return st.size();\n }\n};\n```
3
0
['C++']
0
minimum-add-to-make-parentheses-valid
simple and easy understand solution
simple-and-easy-understand-solution-by-s-da8a
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n int minAddToMakeValid(string s) \n {\n string ok;\n
shishirRsiam
NORMAL
2024-04-17T03:54:33.658594+00:00
2024-04-17T03:54:33.658625+00:00
1,078
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) \n {\n string ok;\n int ans = 0;\n for(char c:s)\n {\n if(c==\'(\') ok += c;\n else \n {\n if(ok.empty()) ans++;\n else ok.pop_back();\n }\n }\n return ok.size() + ans;\n }\n};\n```
3
0
['String', 'Stack', 'Greedy', 'C', 'C++', 'Java', 'C#']
4
minimum-add-to-make-parentheses-valid
✅NO STACK (SC: O(1))✅||🔥Simple & EASY Soln🔥|| Beats 100% - With Explanation
no-stack-sc-o1simple-easy-soln-beats-100-25gh
Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe intution is very simple. We check if the expression is balanced at any point whil
priyankarkoley
NORMAL
2024-04-06T08:30:32.000024+00:00
2024-04-06T08:30:32.000052+00:00
211
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe intution is very simple. We check if the expression is balanced at any point while we traverse through the string. To check for extra `)`, we just check while we are moving left to right, it is currently balanced and we get closing parenthesis `)`, then it is surely extra. Then we check for extra `(` by traversing right to left. At any point if it unbalanced and we get another `(`, we can surely say that is extra. We mark both type of extra parenthesis while traversing. And then count them at last in another traversal.\n\nAt any point unbalanced_open keeps the count of unbalanced open parenthesis `(`. If +ve, there is extra `(`. If -ve, there is extra `)`.\n\n---\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe steps to approach this problem is ->\n\n1. Keep a variable that counts unbalanced or extra `(`. Here `unbalanced_open`.\n2. Traverse the string left to right.\n - If `s[i]` is a `(` increase `unbalanced_open` by one.\n - If `s[i]` is a `)`\n - If the expression is already balanced (`unbalanced_open==0`) we can mark it extra by `s[i]=\'#\'`.\n - Otherwise decrease `unbalanced_open` by one.\n3. Traverse the string right to left.\n - If `s[i]` is a `(` and the expression is already unbalanced with opening parenthesis`(` (`unbalanced_open>0`)\n - we can mark it extra by `s[i]=\'#\'`.\n - Reduce unbalanced_open by one.\n4. Iterate through the string, and if any char is marked `s[i]==\'#\'`, increase `count` by 1.\n\n---\n# Bonus\nThere is a very similar problem to this. You can checkout [that](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/solutions/4980922/no-stack-simple-intution-bonus-tips-simple-2-traversal-c-soln-beats-99-with-explanation) with very same logic.\n\n---\n# Complexity\n- Time complexity: ***O(n)***\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ***O(1)***\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n int unbalanced_open=0;\n for(char &c:s){\n if(c==\'(\')unbalanced_open++;\n else if(c==\')\'){\n if(unbalanced_open==0)c=\'#\';\n else unbalanced_open--;\n }\n }\n for(int i=s.size()-1; i>=0; i--){\n if(unbalanced_open>0 && s[i]==\'(\'){\n s[i]=\'#\';\n unbalanced_open--;\n }\n }\n int count=0;\n for(int i=0; i<s.size(); i++)\n if(s[i]==\'#\')\n count++;\n return count;\n }\n};\n```\n\n---\n\n\n***HOPE MY ANSWER HELPS. BY THE WAY, ONE UPVOTE WOULD MAKE MY DAY.***\n\n![dea9605d2a30ab9ade42d3fa17c208db.jpg](https://assets.leetcode.com/users/images/3a985ed0-6352-4d67-9a9d-169ffec8276d_1712392043.8603547.jpeg)\n
3
0
['C++']
0
minimum-add-to-make-parentheses-valid
Simple java using Stack
simple-java-using-stack-by-tryambak_triv-uir0
\n# Code\n\nclass Solution {\n public int minAddToMakeValid(String s) {\n Stack<Character> st= new Stack<Character>();\n char ch[]= s.toCharArr
Tryambak_Trivedi
NORMAL
2024-03-15T05:35:01.063731+00:00
2024-03-15T05:35:01.063756+00:00
15
false
\n# Code\n```\nclass Solution {\n public int minAddToMakeValid(String s) {\n Stack<Character> st= new Stack<Character>();\n char ch[]= s.toCharArray();\n int c=0;\n for(int i=0;i< ch.length;i++)\n {\n if(ch[i]==\'(\')\n {\n st.push(ch[i]);\n }\n else\n {\n if(!st.isEmpty())\n {\n st.pop();\n }\n else\n c++;\n }\n }\n c+=st.size();\n return(c);\n \n }\n}\n```
3
0
['Java']
0
minimum-add-to-make-parentheses-valid
0ms | Beginner Friendly C++ Sol with EXPLANATION
0ms-beginner-friendly-c-sol-with-explana-e5mh
Intuition\nConsider test case \'()))((\'. For sure we need a stack to solve this problem. If you just do a simple dry run for this test case, you\'ll get to kno
durvesh_jazz
NORMAL
2024-02-19T04:14:41.843019+00:00
2024-02-19T04:14:41.843059+00:00
301
false
# Intuition\nConsider test case \'**()))((**\'. For sure we need a stack to solve this problem. If you just do a simple dry run for this test case, you\'ll get to know the problem easily. For each opening bracket, we need a corresponding closing bracket. Basically we need to maintain only opening brackests in the stack.\n\n# Approach\n1. \'(\' push onto the stack.\n2. \')\' pop from the stack iff the stack is not empty.\n3. For step 2, if the incoming operator is a closing bracket and the stack is empty, we can conclude that there is not matching \'(\' that exists in the stack (as we are only maintaining \'(\' in the stack).\nso we do a cnt++\n4. **At last(one more case), if the stack contains only \'(\' brackets at last and the string exhausts, we can for sure conclude that no matching \')\' brackets were found.**\n5. Therefore while returning, we return the **sum of cnt and the size of the stack.**\n\n# Complexity\n- Time complexity:\nTraversal: O(N)\nPush, Pop: O(1)\n**Final: O(N)**\n\n- Space complexity:\nSC: O(N) \nif the string contains all the opening parenthesis\n\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char> st;\n int cnt = 0;\n for(char ch : s) {\n if(ch == \'(\') {\n st.push(ch);\n } \n else if(ch == \')\') {\n if(st.empty()) {\n cnt++;\n } \n else {\n st.pop(); \n }\n }\n }\n return cnt + st.size();\n }\n};\n\n```
3
0
['Stack', 'C++']
1
minimum-add-to-make-parentheses-valid
C++ || Detailed Explanation || Easy approach
c-detailed-explanation-easy-approach-by-qj0ct
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1) We have to check for
atuly31
NORMAL
2023-10-22T17:36:46.732003+00:00
2023-10-25T16:45:07.263578+00:00
95
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) We have to check for opening bracket into the string, if we find that we will push that into the stack \n2) In case of closing bracket if we find corresponding opening bracket then we will pop opening bracket from the stack \n3) If the stack is empty then we just count how many idle brackets are left and add then we will add it with the size of stack to get the number of idle brackets to make it valid \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 minAddToMakeValid(string s) {\n stack<char> s1;\n int c =0;\n for(int i=0;i<s.size();i++){\n if(s[i] == \'(\') {\n s1.push(s[i]);\n }\n else {\n if(s1.empty() == false){\n s1.pop();\n \n }\n else c++ ;\n }\n }\n \n return c+s1.size();\n \n }\n};\n```\n# **PLEASE UPVOTE IF YOU LIKE MY APPROACH **
3
0
['C++']
2
minimum-add-to-make-parentheses-valid
Most ever Easy Solution
most-ever-easy-solution-by-saim75-3jw2
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
saim75
NORMAL
2023-10-09T11:57:19.116148+00:00
2023-10-09T11:57:19.116168+00:00
68
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:\n def minAddToMakeValid(self, s: str) -> int:\n open_count = 0 \n close_count = 0 \n\n for char in s:\n if char == \'(\':\n open_count += 1\n elif char == \')\':\n if open_count > 0:\n open_count -= 1\n else:\n close_count += 1\n\n return open_count + close_count\n```
3
0
['String', 'Stack', 'Greedy', 'Python3']
0
minimum-add-to-make-parentheses-valid
[Java] Simple one pass 100% solution
java-simple-one-pass-100-solution-by-ytc-b8l9
java\nclass Solution {\n public int minAddToMakeValid(String s) {\n int left = 0, right = 0;\n\n for(int i = 0; i < s.length(); ++i) {\n
YTchouar
NORMAL
2023-09-28T00:10:52.296322+00:00
2023-09-28T00:10:52.296348+00:00
366
false
```java\nclass Solution {\n public int minAddToMakeValid(String s) {\n int left = 0, right = 0;\n\n for(int i = 0; i < s.length(); ++i) {\n if(s.charAt(i) == \'(\')\n left++;\n else if(left > 0)\n left--;\n else\n right++;\n }\n\n return left + right;\n }\n}\n```
3
0
['Java']
0
minimum-add-to-make-parentheses-valid
Easy Java solution | 2 methods Explained with and without using Stack ✨
easy-java-solution-2-methods-explained-w-62y2
\n Add your space complexity here, e.g. O(n) \n\n# Code\n\nclass Solution {\n public int minAddToMakeValid(String s) {\n Stack<Character> stack = new St
202151151
NORMAL
2023-07-19T21:18:49.218122+00:00
2023-07-19T21:18:49.218156+00:00
305
false
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minAddToMakeValid(String s) {\n Stack<Character> stack = new Stack<>();\n int i=0;\n while(i<s.length()){\n if(s.charAt(i)==\')\'){\n if(!stack.isEmpty() && stack.peek()==\'(\'){\n stack.pop();\n }\n else{\n stack.push(s.charAt(i));\n }\n }\n \n else{\n stack.push(s.charAt(i));\n \n }\n \n i++;\n }\n return stack.size();\n }\n}\n\n//======================Second Approach=============================\n\nclass Solution {\n public int minAddToMakeValid(String s) {\n int left =0;\n int right =0;\n for(int i=0; i<s.length(); i++){\n if(s.charAt(i)==\'(\'){\n left++;\n }\n else{\n if(left>0) left--;\n else right++;\n }\n }\n return left+right;\n }\n}\n```
3
0
['String', 'Stack', 'Java']
1
minimum-add-to-make-parentheses-valid
Easy JAVA Solution | 100% | O(n) time , O(1)space
easy-java-solution-100-on-time-o1space-b-amyt
Intuition\nat a particular place if we are lacking open brackets that mean we need opening bracket for the current closing bracket to balance and Simply we just
Sumit-pandey
NORMAL
2023-07-11T17:03:04.459393+00:00
2023-07-11T17:03:04.459409+00:00
292
false
# Intuition\nat a particular place if we are lacking open brackets that mean we need opening bracket for the current closing bracket to balance and Simply we just add the extra open brackets... \nAt last if we are left with some open brackets we directly add the in out moves..\n\n# Complexity\n- Time complexity: O(n) , n=String length\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minAddToMakeValid(String s) {\n //counting open brackets\n int opn=0;\n //record of extra moves we need\n int mvs=0;\n for(char ch : s.toCharArray()){\n //if ch==\'(\' we add 1 to opn\n if(ch==\'(\')opn++;\n //if ch==\')\' we have two options\n if(ch==\')\'){\n //if we have enough brackets we decrement from them\n //else we need an extra bracket\n if(opn>0)opn--;\n else mvs++;\n }\n }\n //atlast add all open brackets left\n if(opn!=0)mvs+=opn;\n return mvs;\n }\n}\n```
3
0
['String', 'Sliding Window', 'Java']
0
minimum-add-to-make-parentheses-valid
Easy C++ Solution using Stack.
easy-c-solution-using-stack-by-bunkorner-57fn
Approach\n Describe your approach to solving the problem. \nDefine a stack,\nPush all the \'(\' that come in the way.\nIf you encounter \')\' there\'s nothing i
bunkorner
NORMAL
2023-06-19T09:19:46.503624+00:00
2023-06-19T09:19:46.503641+00:00
1,309
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nDefine a stack,\nPush all the \'(\' that come in the way.\nIf you encounter \')\' there\'s nothing in the stack yet, so increase the counter, as we have to add \'(\' to every corresponding \')\'.\nIf stack is non-empty pop an \'(\' from it.\n\nAt last add the counter and stack size as we have to add \')\' to every \'(\' in the stack.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe traversed the string once so, $$O(n)$$.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nStack in worst case can use $$O(n)$$ space.\n\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<int> st;\n int cnt=0;\n for(auto a:s)\n {\n if(a==\'(\')\n st.push(a);\n else if(a==\')\')\n {\n if(!st.empty())\n st.pop();\n else\n cnt++;\n }\n }\n return cnt+st.size();\n }\n};\n```
3
0
['C++']
0
minimum-add-to-make-parentheses-valid
CPP STACK SOL
cpp-stack-sol-by-chayannn-bagj
\n\n\n# Code\n\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char>st;\n st.push(s[0]);\n for(int i=1;i<s.size()
Chayannn
NORMAL
2023-05-19T04:50:51.559558+00:00
2023-05-19T04:50:51.559603+00:00
164
false
![UPvote.jpg](https://assets.leetcode.com/users/images/9632ff40-c308-4840-98f2-906dac7538e0_1684471830.8581393.jpeg)\n\n\n# Code\n```\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char>st;\n st.push(s[0]);\n for(int i=1;i<s.size();i++){\n if (!st.empty() && st.top() == \'(\' && s[i] == \')\') st.pop();\n else st.push(s[i]);\n }\n return st.size();\n }\n};\n```
3
0
['Stack', 'C++']
0
count-subtrees-with-max-distance-between-cities
[C++/Python] Bitmask try all subset of cities - Clean & Concise - O(2^n * n)
cpython-bitmask-try-all-subset-of-cities-vs9m
Solution 1: Bitmask + Floyd Warshall\n- Using Floyd-Warshall algorithm to calculate minimum distance between any node to any other node.\n- Since n <= 15, there
hiepit
NORMAL
2020-10-11T04:20:43.186584+00:00
2020-10-13T01:52:46.712182+00:00
7,371
false
**Solution 1: Bitmask + Floyd Warshall**\n- Using Floyd-Warshall algorithm to calculate minimum distance between any node to any other node.\n- Since `n <= 15`, there is a maximum `2^15` subset of cities numbered from `1` to `n`.\n- For each of subset of cities:\n\t- Our subset forms a subtree if and only if `number of edges = number of cities - 1`\n\t- Iterate all pair of cities to calculate `number of edges `, `number of cities`, `maximum distance between any 2 cities`\n\nComplexity\n- Time: `O(2^n * n^2)`\n- Space: `O(n^2)`\n\n<iframe src="https://leetcode.com/playground/fr3jcKi9/shared" frameBorder="0" width="100%" height="660"></iframe>\n\n**Solution 2: Bitmask + BFS every cities**\n- Since `n <= 15`, there is a maximum `2^15` subset of cities numbered from `1` to `n`.\n- For each of subset of cities, we calculate the **maximum distance** between any two cities in our subset.\n\t- For each `city` in our subset:\n\t\t- Using `bfs()` or `dsf()` to calculate distance between `city` to other cities in subset.\n\t\t- If `citiy` can\'t reach to any other cities then subset form an **invalid subtree.**\n\t- Return distance of 2 cities with maxium distance.\n\nComplexity\n- Time: `O(2^n * n^2)`\n- Space: `O(n^2)`\n\n<iframe src="https://leetcode.com/playground/PLUBYjTt/shared" frameBorder="0" width="100%" height="650"></iframe>\n\n**Solution 3: Bitmask + Diamter of the tree (BFS 2 times)**\n- Since `n <= 15`, there is a maximum `2^15` subset of cities numbered from `1` to `n`.\n- For each of subset, we calculate the **maximum distance** between any two cities in our subset. \n- **Maximum distance** between any two cities in our subset (subset must be a subtree) is the **diameter** of the tree. Can reference: https://leetcode.com/problems/tree-diameter/\n\nComplexity\n- Time: `O(2^n * n)`\n- Space: `O(n^2)`\n\n<iframe src="https://leetcode.com/playground/beLfGngX/shared" frameBorder="0" width="100%" height="800"></iframe>\n\nCredit [@siranjoy](https://leetcode.com/siranjoy/) for reminding me this approach.
109
1
[]
13
count-subtrees-with-max-distance-between-cities
If you find it is difficult to understand the solution of this problem like me,
if-you-find-it-is-difficult-to-understan-6h9z
Hope my post can help you to clearly understand the solution. \n\n1. You should first solve problem #543 diameter of binary tree. \n\nGiven one and only one tre
runningXin
NORMAL
2020-10-16T18:35:23.342776+00:00
2020-11-02T18:25:43.786795+00:00
2,570
false
Hope my post can help you to clearly understand the solution. \n\n1. You should first solve problem #543 diameter of binary tree. \n\nGiven one and only one tree, you should be able to understand how we leverage DFS to traverse the tree in postorder fashion and calculate the diameter THROUGH a/every single node to get the diameter which is simply concatenate left and right together\n\n2. Now you can move on to #1245 Tree Diameter\n\nIn this problem, the difference/difficult is, now, we don\'t just have a BINARY tree, we actually have a graph, since a node in this graph not just have left child and right child, we should pick the TOP TWO max incoming path and concatenate them together (other than simply add left + right) \n\nWe need to iterate every neighbor of the current node to get the max diameter through that node. \n\n3. 1617. Count Subtrees With Max Distance Between Cities\n\nNow, we don\'t just have one graph/tree, we have to exaustive every subtree/subset. \n(Now you need to review another knowledge if you don\'t possess -- bitmasking) \n\nYou need to get back to #78 subsets to understand how to use bitmasking to contruct subset, once you understand the j & 1<<i, things are much easier now. \n\nNow to solve this problem is only put the above code snippet together. \n\nHope it helps, thanks. \n\n```\nclass Solution {\n int max = 0;\n \n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n //result[] = {1-indexed ... };\n \n int [] result = new int[n-1];\n //build graph\n Map<Integer, List<Integer>> graph = new HashMap<>();\n for(int[] e : edges ){\n graph.computeIfAbsent(e[0], (k)->(new ArrayList<>())).add(e[1]);\n graph.computeIfAbsent(e[1], (k)->(new ArrayList<>())).add(e[0]);\n }\n \n //Get all the valid subtrees/subsets \n for(int i = 0; i < (1 << n); i++){\n List<Integer> subtree = new ArrayList<>();\n //use bitmasking to construct every single subset/subtree\n for(int j = 0; j < n; j++){\n if((i & (1 << j)) != 0 ) //this bit is 1, means this node is chosen \n subtree.add(j + 1); //cities numbered from 1 \n }\n \n \n //now we need to evaluate if this subtree is valid\n int edge_number = 0;\n for(int[] e : edges ){\n if(subtree.contains(e[0]) && subtree.contains(e[1]))\n edge_number ++;\n }\n \n if(edge_number < 1 || subtree.size() != edge_number + 1 )\n continue; //not valid subtree\n \n //till here, we have a valid subtree, and we need to use DFS to get the max diameter\n Set<Integer> visited = new HashSet<>();\n max = 0;\n visited.add(subtree.get(0));\n dfs(subtree.get(0), graph, subtree, visited); \n result[max - 1]++;\n }\n \n return result;\n }\n \n private int dfs( int current, Map<Integer, List<Integer>> graph, List<Integer> subtree, Set<Integer> visited){\n \n int m1 = 0;\n int m2 = 0;\n \n for(int neighbor : graph.get(current)){\n if(!visited.contains(neighbor) && subtree.contains(neighbor) ){\n visited.add(neighbor);\n int depth = dfs(neighbor, graph, subtree, visited);\n if(depth > m1){\n m2 = m1;\n m1 = depth;\n }else if(depth > m2)\n m2 = depth;\n }\n \n }\n \n max = Math.max(max, m1 + m2);\n return m1+1;\n }\n}\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n
56
0
[]
7
count-subtrees-with-max-distance-between-cities
[C++/Python] Floyd-Warshall + Enumerate Subsets O(2^N * N^2)
cpython-floyd-warshall-enumerate-subsets-k6s9
Ideas\n\n There are only 2^15 possible subsets of nodes. We can check them all.\n A subset of size k is a subtree if-and-only-if there are k-1 edges between pai
karutz
NORMAL
2020-10-11T07:21:49.785999+00:00
2020-10-13T09:55:19.410956+00:00
2,188
false
**Ideas**\n\n* There are only `2^15` possible subsets of nodes. We can check them all.\n* A subset of size `k` is a subtree if-and-only-if there are `k-1` edges between pairs in the subset.\n\n**Algorithm**\n\n1. Use [Floyd-Warshall Algorithm](https://en.m.wikipedia.org/wiki/Floyd\u2013Warshall_algorithm) to find all shortest paths.\n2. Brute force all possible subsets and count subtrees with diameter `d`.\n\n**Python**\n```python\nfrom itertools import combinations, permutations\n\nclass Solution:\n def countSubgraphsForEachDiameter(self, n, edges):\n g = [[999 for _ in range(n)] for _ in range(n)]\n for [i, j] in edges:\n g[i - 1][j - 1], g[j - 1][i - 1] = 1, 1\n\n for k, i, j in permutations(range(n), 3):\n g[i][j] = min(g[i][j], g[i][k] + g[k][j])\n\n ans = [0 for _ in range(n - 1)]\n for k in range(2, n + 1):\n for s in combinations(range(n), k):\n e = sum(g[i][j] for i, j in combinations(s, 2) if g[i][j] == 1)\n d = max(g[i][j] for i, j in combinations(s, 2))\n if e == k - 1:\n ans[d - 1] += 1\n \n return ans\n```\n**C++**\n```c++\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> g(n, vector<int>(n, 999));\n for (auto &e : edges) {\n int i = e[0] - 1;\n int j = e[1] - 1;\n g[i][j] = g[j][i] = 1;\n }\n \n for (int k = 0; k < n; k++) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n g[i][j] = min(g[i][j], g[i][k] + g[k][j]);\n }\n }\n }\n \n vector<int> ans(n - 1, 0);\n for (int s = 0; s < (1 << n); s++) {\n int k = __builtin_popcount(s);\n int e = 0;\n int d = 0;\n for (int i = 0; i < n; i++) if (s & (1 << i)) {\n for (int j = i + 1; j < n; j++) if (s & (1 << j)) {\n e += g[i][j] == 1;\n d = max(d, g[i][j]);\n }\n }\n if (e == k - 1 && d > 0) {\n ans[d - 1]++;\n }\n }\n \n return ans;\n }\n};\n```\nNote: `__builtin_popcount(s)` gets the number of 1 bits in `s`.
52
0
[]
5
count-subtrees-with-max-distance-between-cities
C++ Two Approaches
c-two-approaches-by-votrubac-1zff
I overdid this one - wasted a lot of time trying to find a practical approach. Instead, I should have focused on the brute-force... I checked constraints this t
votrubac
NORMAL
2020-10-11T23:40:53.075397+00:00
2020-10-12T04:16:27.321128+00:00
3,145
false
I overdid this one - wasted a lot of time trying to find a practical approach. Instead, I should have focused on the brute-force... I checked constraints this time, but was still stuborn somehow.\n \n We enumerate all combinations of nodes (up to 2 ^ 16 combinations), then check if these nodes form a tree. If they do, get the diameter of the tree. Track and return the count of each diameter.\n\n#### Approach 1: DFS\nWe first build an adjacency list. Then, we enumerate all possible combinations of nodes. For each combination, we pick a node and do DFS. While doing DFS, we calculate the tree diameter, and also count nodes. We count nodes to make sure that all nodes in the combination were reached, so they form a tree.\n\n```cpp\nint dfs(vector<vector<int>> &al, int mask, int i, int &n, int &res) {\n int dia = 0, max_dia = 0;\n ++n;\n for (auto j : al[i])\n if (mask & (1 << j)) {\n int dia = 1 + dfs(al, mask ^ (1 << j), j, n, res);\n res = max(res, dia + max_dia);\n max_dia = max(max_dia, dia);\n }\n return max_dia;\n}\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> al(n);\n for (auto &e : edges) {\n al[e[0] - 1].push_back(e[1] - 1);\n al[e[1] - 1].push_back(e[0] - 1);\n }\n vector<int> res(n - 1);\n for (int s = 3; s < 1 << n; ++s) {\n for (int i = 0; i < n; ++i)\n if (s & (1 << i)) {\n int nodes = 0, dia = 0;\n dfs(al, s ^ (1 << i), i, nodes, dia);\n if (dia > 0 && nodes == bitset<16>(s).count())\n ++res[dia - 1];\n break;\n }\n }\n return res;\n}\n```\n**Complexity Analysis**\n- Time: O(n * 2 ^ n). We enumerate 2 ^ n trees and traverse each tree once.\n- Memory: O(n). Because it\'s a tree, the number of edges is n - 1, so we our adjacency list need 2n -1 space.\n\n#### Approach 2: Floyd-Warshall\nThis approach is more complicated and a bit slower. Here, we first build an adjacency matrix with the distance between each node using Floyd-Warshall algorithm O(n ^ 3).\n\nThen, instead of doing DFS, we enumerate all pairs of nodes, and lookup the distance in the adjacency matrix. We also need to count the edges (`d[i][j] == 1`) to make sure all these nodes are in the same subtree (`nodes == edges - 1`).\n\n```cpp\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> d(n, vector<int>(n, n));\n for (auto &e : edges)\n d[e[0] - 1][e[1] - 1] = d[e[1] - 1][e[0] - 1] = 1;\n for (int k = 0; k < n; ++k)\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n d[i][j] = min(d[i][j], d[i][k] + d[k][j]);\n vector<int> res(n - 1, 0);\n for (int s = 0; s < 1 << n; ++s) {\n int max_depth = 0, nodes = 0, edges = 0;\n for (int i = 0; i < n; ++i)\n if (s & (1 << i)) {\n ++nodes;\n for (int j = i + 1; j < n; ++j)\n if (s & (1 << j)) {\n edges += d[i][j] == 1;\n max_depth = max(max_depth, d[i][j]);\n }\n }\n if (edges == nodes - 1 && max_depth > 0)\n ++res[max_depth - 1];\n }\n return res;\n}\n```\n**Complexity Analysis**\n- Time: O(n ^ 2 * 2 ^ n). We enumerate 2 ^ n trees, and enumerate all pairs of nodes.\n- Memory: O(n ^ 2) for the adjacency matrix.
41
1
[]
8
count-subtrees-with-max-distance-between-cities
C++ O(n * 2 ^ n) solution. bitmask + DFS, with explanation.
c-on-2-n-solution-bitmask-dfs-with-expla-al4i
\n\nhere is the idea:\n1. iterate all the possible subtree from 1 to (1 << n - 1), the positions of 1 bits are the tree node ID.\n2. use dfs to calcuate the max
chejianchao
NORMAL
2020-10-11T04:00:19.952255+00:00
2020-10-11T17:33:41.455773+00:00
2,050
false
\n\nhere is the idea:\n1. iterate all the possible subtree from 1 to (1 << n - 1), the positions of `1` bits are the tree node ID.\n2. use dfs to calcuate the maximum distance for the subtree.\n3. verfiy if the subtree is valid. once we visited a node then we clear the specific bit in the subtree, after finishing dfs, if subtree == 0, that means it is a valid subtree.\n4. update ans by the maximum distance.\n\n```\nclass Solution {\npublic:\n unordered_set<int> g[16];\n int dfs(int u, int p, int &subtree, int &mx) {\n subtree = subtree ^ (1 << (u - 1)); //clear visited Node bit.\n int a = 0, b = 0;\n for(auto v : g[u]) {\n if(v == p) continue;\n if((subtree & (1 << (v - 1))) == 0) continue; //the next node is not included in the subtree, ignore this node.\n int res = dfs(v, u, subtree, mx) + 1;\n if(res > a) {\n b = a; a = res;\n } else if(res > b) {\n b = res;\n }\n }\n mx = max(mx, a + b); //get the maximum distance in the subtree.\n return a; //return the longest path from current node.\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<int> ans(n - 1);\n for(auto &e : edges) { //build graph.\n g[e[0]].insert(e[1]);\n g[e[1]].insert(e[0]);\n }\n int size = 1 << n;\n for(int i = 1; i < size; ++i) {\n if(((i - 1) & i) == 0) continue; //we don\'t need to calculate the subtree which have one node only.\n int subtree = i;\n int u = 0;\n int mx = 0;\n for(int j = 0; j < n; ++j) { // to get the start node.\n if((1 <<j) & i) {\n u = j + 1;\n break;\n }\n }\n int res = dfs(u, -1, subtree, mx);\n if(subtree == 0) {\n ++ans[mx - 1];\n }\n }\n return ans;\n }\n};\n```
21
3
[]
8
count-subtrees-with-max-distance-between-cities
C++ Explaination with comments
c-explaination-with-comments-by-kaushik8-vimz
\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n //INT_MAX/2-1 used to avoid overflow\n
kaushik8511
NORMAL
2020-10-12T12:59:30.828930+00:00
2021-01-12T15:21:40.552903+00:00
735
false
```\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n //INT_MAX/2-1 used to avoid overflow\n vector<vector<int>> graph(n, vector<int>(n, INT_MAX/2-1));\n for (auto e : edges) {\n int u = e[0] - 1, v = e[1] - 1;\n graph[u][v] = graph[v][u] = 1;\n }\n \n //floyed-warshall algorithm\n for (int k = 0; k < n; k++) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);\n }\n }\n }\n \n vector<int> res(n-1, 0);\n \n \n /* Check for each combination of nodes and see if it\'s a subtree or not.\n If it\'s a subtree then see maximum distance that can be reached.*/\n \n //Each subtree\n //sub = subtree\n for (int sub = 0; sub < (1 << n); sub++) {\n // Number of nodes = nodes\n int nodes = __builtin_popcount(sub);\n // edges\n int edges = 0;\n //dist = distance\n int dist = 0;\n for (int i = 0; i < n; i++)\n if (sub & (1 << i)) {\n for (int j = i + 1; j < n; j++) \n if (sub & (1 << j)) {\n // if i to j edge increment e\n edges += graph[i][j] == 1;\n // maximum distance\n dist = max(dist, graph[i][j]);\n }\n }\n // chech its a subtree and distance > 0 if it\'s then its a subtree having max d distance\n if (edges == nodes - 1 && dist > 0) {\n res[dist - 1]++;\n }\n }\n \n return res;\n\t\t//Please upvote\n }\n};\n```
13
2
['Graph', 'C', 'Bitmask']
2
count-subtrees-with-max-distance-between-cities
💥💥Beats 100% on runtime and memory [EXPLAINED]
beats-100-on-runtime-and-memory-explaine-toxc
Intuition\nThe problem revolves around understanding trees as a special type of graph where there\u2019s a unique path between any two nodes. Each subtree forme
r9n
NORMAL
2024-10-01T21:08:16.110541+00:00
2024-10-01T21:08:16.110567+00:00
60
false
# Intuition\nThe problem revolves around understanding trees as a special type of graph where there\u2019s a unique path between any two nodes. Each subtree formed by selecting nodes can have various distances between its furthest nodes, and our goal is to count how many of these subtrees correspond to each possible maximum distance.\n\n\n# Approach\nWe first build a graph from the edges, then iterate through all possible subsets of nodes using bit manipulation to determine which nodes are included, checking if the subset forms a single connected component, and if so, calculating its diameter (maximum distance) using depth-first search; we store these counts in an array corresponding to their diameters.\n\n\n# Complexity\n- Time complexity:\nO(n . 2n) because we evaluate all subsets (up to 2n) and check the connected components and diameters for each subset.\n\n\n- Space complexity:\nO(n) for storing the graph and auxiliary data structures like visited nodes and depths during the DFS.\n\n\n# Code\n```typescript []\n/**\n * Calculate the diameter of the tree formed by the selected nodes.\n * @param graph - The adjacency list representing the graph.\n * @param nodes - The nodes selected for the subtree.\n * @param n - The total number of nodes.\n * @returns The diameter of the tree.\n */\nfunction getTreeDiameter(graph: Map<number, number[]>, nodes: number[], n: number): number {\n if (nodes.length === 1) return 0; // A single node has no diameter\n\n const root = nodes[0]; // Start DFS from the first node\n const depths = Array(n).fill(0); // Array to store depths of each node\n const visited = new Set<number>(); // Set to track visited nodes\n\n // Depth-first search to calculate depths\n function dfs(node: number, depth: number): void {\n if (visited.has(node)) return; // Return if already visited\n visited.add(node);\n depths[node] = depth; // Set the depth for the current node\n for (const to of graph.get(node) || []) {\n if (!visited.has(to) && nodes.includes(to)) {\n dfs(to, depth + 1); // Recursive DFS for adjacent nodes\n }\n }\n }\n\n // Second DFS to find the maximum distance from the furthest node\n function dfs2(node: number): number {\n if (visited.has(node)) return 0; // Return if already visited\n visited.add(node);\n let dist = 0;\n for (const to of graph.get(node) || []) {\n if (!visited.has(to) && nodes.includes(to)) {\n dist = Math.max(dist, dfs2(to) + 1); // Find max distance\n }\n }\n return dist; // Return the maximum distance found\n }\n\n // Perform first DFS to calculate depths\n dfs(root, 0);\n let maxDepth = -1;\n let furthestNode = -1;\n\n // Identify the furthest node from the root\n for (const node of nodes) {\n if (depths[node] > maxDepth) {\n maxDepth = depths[node];\n furthestNode = node;\n }\n }\n\n visited.clear(); // Clear visited set for the second DFS\n return dfs2(furthestNode); // Get the diameter from the furthest node\n}\n\n/**\n * Get the size of the connected component for the selected nodes.\n * @param graph - The adjacency list representing the graph.\n * @param nodes - The nodes selected for the component.\n * @param n - The total number of nodes.\n * @returns The size of the connected component.\n */\nfunction getComponentSize(graph: Map<number, number[]>, nodes: number[], n: number): number {\n let count = 0; // Count of connected components\n const visited = Array(n).fill(false); // Array to track visited nodes\n\n // Depth-first search to mark connected nodes\n function dfs(node: number): void {\n if (visited[node]) return; // Return if already visited\n visited[node] = true; // Mark the node as visited\n for (const to of graph.get(node) || []) {\n if (!visited[to] && nodes.includes(to)) {\n dfs(to); // Recursive DFS for adjacent nodes\n }\n }\n }\n\n // Iterate through selected nodes to count components\n for (const node of nodes) {\n if (!visited[node]) {\n dfs(node); // Perform DFS for each unvisited node\n count += 1; // Increment count for each component found\n }\n }\n return count; // Return the total number of components\n}\n\n/**\n * Count the number of subgraphs for each diameter.\n * @param n - The total number of nodes.\n * @param edges - The edges connecting the nodes.\n * @returns An array with counts of subgraphs for each diameter.\n */\nconst countSubgraphsForEachDiameter = function (n: number, edges: number[][]): number[] {\n const graph = new Map<number, number[]>(); // Graph representation\n const distMap = new Map<number, number[][]>(); // Map to store distances and corresponding nodes\n\n // Build the graph from the edges\n for (const [a, b] of edges) {\n const u = a - 1; // Convert to 0-based index\n const v = b - 1;\n if (!graph.has(u)) {\n graph.set(u, []);\n }\n if (!graph.has(v)) {\n graph.set(v, []);\n }\n graph.get(u)!.push(v); // Add edge to the graph\n graph.get(v)!.push(u);\n }\n\n // Iterate over all subsets of nodes using bit masking\n for (let mask = 0; mask < (1 << n); mask++) {\n const select: number[] = []; // Selected nodes for the current subset\n for (let j = 0; j < n; j++) {\n if (mask & (1 << j)) {\n select.push(j); // Add the node if it\'s included in the subset\n }\n }\n\n // Get the size of the connected component for the selected nodes\n const size = getComponentSize(graph, select, n);\n if (size === 1) { // Only consider single components\n const dist = getTreeDiameter(graph, select, n); // Calculate tree diameter\n if (!distMap.has(dist)) {\n distMap.set(dist, []);\n }\n distMap.get(dist)!.push(select); // Store the nodes for the diameter\n }\n }\n\n const ans = Array(n - 1).fill(0); // Initialize answer array\n for (let d = 1; d <= n - 1; d++) {\n const count = distMap.get(d)?.length || 0; // Count for diameter d\n ans[d - 1] = count; // Store in result\n }\n return ans; // Return the final counts for each diameter\n};\n\n```
8
0
['TypeScript']
0
count-subtrees-with-max-distance-between-cities
💥💥Beats 100% on runtime and memory [EXPLAINED]
beats-100-on-runtime-and-memory-explaine-x320
\n\n# Intuition\nThe problem revolves around understanding trees as a special type of graph where there\u2019s a unique path between any two nodes. Each subtree
r9n
NORMAL
2024-10-01T21:12:49.469464+00:00
2024-10-01T21:12:49.469486+00:00
27
false
![image.png](https://assets.leetcode.com/users/images/620257ea-bca4-4c97-9f5d-bae4d47e65f2_1727817136.273814.png)\n\n# Intuition\nThe problem revolves around understanding trees as a special type of graph where there\u2019s a unique path between any two nodes. Each subtree formed by selecting nodes can have various distances between its furthest nodes, and our goal is to count how many of these subtrees correspond to each possible maximum distance.\n\n\n# Approach\nWe first build a graph from the edges, then iterate through all possible subsets of nodes using bit manipulation to determine which nodes are included, checking if the subset forms a single connected component, and if so, calculating its diameter (maximum distance) using depth-first search; we store these counts in an array corresponding to their diameters.\n\n\n# Complexity\n- Time complexity:\nO(n . 2n) because we evaluate all subsets (up to 2n) and check the connected components and diameters for each subset.\n\n\n- Space complexity:\nO(n) for storing the graph and auxiliary data structures like visited nodes and depths during the DFS.\n\n\n# Code\n```typescript []\n/**\n * Calculate the diameter of the tree formed by the selected nodes.\n * @param graph - The adjacency list representing the graph.\n * @param nodes - The nodes selected for the subtree.\n * @param n - The total number of nodes.\n * @returns The diameter of the tree.\n */\nfunction getTreeDiameter(graph: Map<number, number[]>, nodes: number[], n: number): number {\n if (nodes.length === 1) return 0; // A single node has no diameter\n\n const root = nodes[0]; // Start DFS from the first node\n const depths = Array(n).fill(0); // Array to store depths of each node\n const visited = new Set<number>(); // Set to track visited nodes\n\n // Depth-first search to calculate depths\n function dfs(node: number, depth: number): void {\n if (visited.has(node)) return; // Return if already visited\n visited.add(node);\n depths[node] = depth; // Set the depth for the current node\n for (const to of graph.get(node) || []) {\n if (!visited.has(to) && nodes.includes(to)) {\n dfs(to, depth + 1); // Recursive DFS for adjacent nodes\n }\n }\n }\n\n // Second DFS to find the maximum distance from the furthest node\n function dfs2(node: number): number {\n if (visited.has(node)) return 0; // Return if already visited\n visited.add(node);\n let dist = 0;\n for (const to of graph.get(node) || []) {\n if (!visited.has(to) && nodes.includes(to)) {\n dist = Math.max(dist, dfs2(to) + 1); // Find max distance\n }\n }\n return dist; // Return the maximum distance found\n }\n\n // Perform first DFS to calculate depths\n dfs(root, 0);\n let maxDepth = -1;\n let furthestNode = -1;\n\n // Identify the furthest node from the root\n for (const node of nodes) {\n if (depths[node] > maxDepth) {\n maxDepth = depths[node];\n furthestNode = node;\n }\n }\n\n visited.clear(); // Clear visited set for the second DFS\n return dfs2(furthestNode); // Get the diameter from the furthest node\n}\n\n/**\n * Get the size of the connected component for the selected nodes.\n * @param graph - The adjacency list representing the graph.\n * @param nodes - The nodes selected for the component.\n * @param n - The total number of nodes.\n * @returns The size of the connected component.\n */\nfunction getComponentSize(graph: Map<number, number[]>, nodes: number[], n: number): number {\n let count = 0; // Count of connected components\n const visited = Array(n).fill(false); // Array to track visited nodes\n\n // Depth-first search to mark connected nodes\n function dfs(node: number): void {\n if (visited[node]) return; // Return if already visited\n visited[node] = true; // Mark the node as visited\n for (const to of graph.get(node) || []) {\n if (!visited[to] && nodes.includes(to)) {\n dfs(to); // Recursive DFS for adjacent nodes\n }\n }\n }\n\n // Iterate through selected nodes to count components\n for (const node of nodes) {\n if (!visited[node]) {\n dfs(node); // Perform DFS for each unvisited node\n count += 1; // Increment count for each component found\n }\n }\n return count; // Return the total number of components\n}\n\n/**\n * Count the number of subgraphs for each diameter.\n * @param n - The total number of nodes.\n * @param edges - The edges connecting the nodes.\n * @returns An array with counts of subgraphs for each diameter.\n */\nconst countSubgraphsForEachDiameter = function (n: number, edges: number[][]): number[] {\n const graph = new Map<number, number[]>(); // Graph representation\n const distMap = new Map<number, number[][]>(); // Map to store distances and corresponding nodes\n\n // Build the graph from the edges\n for (const [a, b] of edges) {\n const u = a - 1; // Convert to 0-based index\n const v = b - 1;\n if (!graph.has(u)) {\n graph.set(u, []);\n }\n if (!graph.has(v)) {\n graph.set(v, []);\n }\n graph.get(u)!.push(v); // Add edge to the graph\n graph.get(v)!.push(u);\n }\n\n // Iterate over all subsets of nodes using bit masking\n for (let mask = 0; mask < (1 << n); mask++) {\n const select: number[] = []; // Selected nodes for the current subset\n for (let j = 0; j < n; j++) {\n if (mask & (1 << j)) {\n select.push(j); // Add the node if it\'s included in the subset\n }\n }\n\n // Get the size of the connected component for the selected nodes\n const size = getComponentSize(graph, select, n);\n if (size === 1) { // Only consider single components\n const dist = getTreeDiameter(graph, select, n); // Calculate tree diameter\n if (!distMap.has(dist)) {\n distMap.set(dist, []);\n }\n distMap.get(dist)!.push(select); // Store the nodes for the diameter\n }\n }\n\n const ans = Array(n - 1).fill(0); // Initialize answer array\n for (let d = 1; d <= n - 1; d++) {\n const count = distMap.get(d)?.length || 0; // Count for diameter d\n ans[d - 1] = count; // Store in result\n }\n return ans; // Return the final counts for each diameter\n};\n\n```
7
0
['TypeScript']
0
count-subtrees-with-max-distance-between-cities
Generate all subsets + use of Floyd-Warshall (easy explanation)
generate-all-subsets-use-of-floyd-warsha-m03z
Since the constraints are very less, we can check every possible subset of nodes.\nFor every subset of nodes we will check if they are forming a subtree then we
pathakG321
NORMAL
2022-07-14T09:21:51.666460+00:00
2022-07-14T13:23:23.303516+00:00
500
false
Since the constraints are very less, we can check every possible subset of nodes.\nFor every subset of nodes we will check if they are forming a `subtree` then we will calculate the maximum distance between every pair of nodes and accordingly update the answer.\n\nNow to calculate the maximum distance between every pair of nodes, we can use `Floyd-Warshall Algorithm` .\n\nSo we can precalculate the distance using `Floyd-Warshall`.\n\nNow important thing is, how can we confirm that all nodes of a subset are forming a subtree. We can do by the basic definition of tree(number of nodes - 1 == number of edges).\nNumber of edges can be calculated by calculating the number of pairs of nodes of distance 1.\nHence, for every pair of nodes we check the distance between them, if distance between them is 1 then we increase the count of edges.\nlet\'s say \n![](https://assets.leetcode.com/uploads/2020/09/21/p1.png)\n\nwe are given this tree and in a subset, nodes comes out to be `{4, 3, 2}`. So if we go for every pair then we get pair like this `(4,3), (4,2) , (3,2)`. Out of these pairs, we have (`(4,2)` and `(3,2)`) between which distance between nodes is `1`. Hence in this case we get `2` as number of edges and my subset size is `3`. So it satisfies the condition `number of nodes - 1 == number of edges`, hence it a valid subtree. \n\n\nAnd while doing so we also keep one `mx` variable to store the maximum distance between them. \n\nCode:- \n```\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n \n // since we need to calculate the distance for every pair of nodes so we need 2-D vector\n vector<vector<int>> distance(n + 1, vector<int>(n + 1, 1e9));\n \n // Now all the nodes which are directly connected they are having a distance 1 between them\n for (auto it : edges) {\n int u = it[0], v = it[1];\n distance[u][v] = 1;\n distance[v][u] = 1;\n }\n // answer array (using 0-based indexing)\n vector<int> ans(n-1, 0);\n \n // floyd-warshall\n for (int k = 1;k <= n;k++) {\n for (int i = 1;i <= n;i++) {\n for (int j = 1;j <= n;j++) {\n distance[i][j] = min(distance[i][k] + distance[k][j], distance[i][j]);\n }\n }\n }\n \n \n // generating all subsets\n \n for (int i = 0;i < (1 << n);i++) { \n vector<int> nodes;\n for (int j = 0;j < n;j++) {\n if (i & (1 << j)) {\n nodes.push_back(j + 1);// storing the nodes\n }\n }\n \n \n \n int mx = -1, countEdges = 0;\n // going for each pair of nodes\n for (int k = 0;k < (int) nodes.size();k++) {\n for (int l = k + 1;l < (int) nodes.size();l++) {\n // if distance between them is 1 it simply means they are connected by an edge.\n if (distance[nodes[k]][nodes[l]] == 1) \n {\n countEdges++;\n }\n // storing the maximum distance between each pair of nodes\n mx = max(mx, distance[nodes[k]][nodes[l]]);\n }\n }\n \n // if number of edges == number of nodes - 1 => it is tree(basic definition of a tree)\n if (countEdges == (int) nodes.size() - 1 && mx > 0) { \n // mx > 0 becoz there can be set of 1 node or 0 node as well, such set won\'t be contributing to answer\n ans[mx-1]++; // storing the count of each maxDistance. using 0-based indexing (mx - 1)\n }\n }\n \n return ans;\n }\n```\n`Time :- O((2^n) * (n^2))`\n
6
0
['C', 'Bitmask']
1
count-subtrees-with-max-distance-between-cities
Python, try all subsets, test if subset is subtree, find diameter of subtree
python-try-all-subsets-test-if-subset-is-2qel
Use dfs to determine whether or not we are a valid subtree. Test connectivity(can reach all), and exclusivity(no extra nodes). To find diameter of tree, run dfs
raymondhfeng
NORMAL
2020-10-11T04:03:02.977038+00:00
2020-10-11T06:43:18.688252+00:00
1,021
false
Use dfs to determine whether or not we are a valid subtree. Test connectivity(can reach all), and exclusivity(no extra nodes). To find diameter of tree, run dfs twice. Since n is small enough can just use a bitmask to enumerate all possible subsets. Tougher to solve if n can grow large. \n```\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n def dfs(edges,start,i): # returns whether or not we are a tree\n seen = set()\n stack = [start]\n while len(stack) > 0:\n curr = stack.pop()\n if curr not in seen:\n seen.add(curr)\n for neigh in edges[curr]:\n stack.append(neigh)\n nodeSet = set()\n for j in range(n):\n if i & (1 << j):\n nodeSet.add(j)\n return nodeSet == seen\n \n def diameter(edges,start): # returns the diameter of tree\n farthest = start\n farthestDist = 0\n seen = set()\n stack = [(start,0)]\n while len(stack) > 0:\n curr,dist = stack.pop()\n if curr not in seen:\n seen.add(curr)\n if dist > farthestDist:\n farthest = curr\n farthestDist = dist\n for neigh in edges[curr]:\n stack.append((neigh,dist+1))\n start = farthest\n farthestDist = 0\n seen = set()\n stack = [(start,0)]\n while len(stack) > 0:\n curr,dist = stack.pop()\n if curr not in seen:\n seen.add(curr)\n if dist > farthestDist:\n farthest = curr\n farthestDist = dist\n for neigh in edges[curr]:\n stack.append((neigh,dist+1))\n return farthestDist\n \n diameterCounts = defaultdict(int)\n for i in range(1,2**n):\n if sum([int(elem) for elem in bin(i)[2:]]) == 1:\n continue\n subTreeEdges = defaultdict(list)\n for edge in edges:\n l,m = edge\n l -= 1\n m -= 1\n if i & (1 << l) and i & (1 << m):\n subTreeEdges[l].append(m)\n subTreeEdges[m].append(l)\n start = None\n for j in range(n):\n if i & (1 << j):\n start = j\n break\n isSubtree = dfs(subTreeEdges,start,i)\n if isSubtree:\n diameterCounts[diameter(subTreeEdges,start)] += 1\n else:\n pass\n \n return [diameterCounts[i] for i in range(1,n)] \n```
6
1
[]
1
count-subtrees-with-max-distance-between-cities
[Java] DFS + BitMask with comments O(N^2*2^N)
java-dfs-bitmask-with-comments-on22n-by-rnbp6
\nclass Solution {\n int[][] dist;\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n\t //precalculate the distance of any two citi
yuhwu
NORMAL
2020-10-11T04:01:51.688017+00:00
2020-10-11T19:06:18.207272+00:00
1,084
false
```\nclass Solution {\n int[][] dist;\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n\t //precalculate the distance of any two cities\n dist = new int[n][n];\n List<Integer>[] graph = new List[n];\n for(int i=0; i<n; i++){\n graph[i] = new ArrayList();\n }\n for(int[] e : edges){\n graph[e[0]-1].add(e[1]-1);\n graph[e[1]-1].add(e[0]-1);\n }\n for(int i=0; i<n; i++){\n calcDist(graph, i, -1, i, 0);\n }\n int[] res = new int[n-1];\n for(int i=1; i<(1<<n); i++){\n int maxDist = 0;\n int oneDistCount = 0;\n int cities = 0;\n\t\t\t//find the max distance between each pair of cities\n for(int j=0; j<n; j++){\n if((i & (1<<j))!=0){\n cities++;\n for(int k=j+1; k<n; k++){\n if((i & (1<<k))!=0){\n maxDist = Math.max(maxDist, dist[j][k]);\n if(dist[j][k]==1){\n oneDistCount++;\n }\n }\n } \n }\n }\n\t\t\t//x cities form a substree if and only if there are x-1 edges among these cities\n if(oneDistCount==cities-1 && maxDist>0) res[maxDist-1]++;\n }\n return res;\n }\n \n public void calcDist(List<Integer>[] graph, int source, int prev, int cur, int d){\n if(prev==cur){\n return;\n }\n dist[source][cur] = d;\n dist[cur][source] = d;\n for(int next : graph[cur]) if(next!=prev){\n calcDist(graph, source, cur, next, d+1);\n }\n }\n}\n```
6
2
[]
2
count-subtrees-with-max-distance-between-cities
[Python] Floyd Warshall and check all subtrees
python-floyd-warshall-and-check-all-subt-5e9k
Uses the Floyd-Warshall algortihm to calculate the shortest path between each pair of nodes. We then check each of the 2^N subtrees of the tree. If the subtre
tw6fgojf5h2w6ai7yo5n
NORMAL
2021-04-01T02:00:24.375918+00:00
2021-04-01T02:00:24.375962+00:00
642
false
Uses the Floyd-Warshall algortihm to calculate the shortest path between each pair of nodes. We then check each of the 2^N subtrees of the tree. If the subtree is connected (checked by performing BFS and checking if all nodes in the subgraph are visisted), then the maximum distance is found using the results from the Floyd-Warshall algoriths. I thought this would be somewhat slow, but it beats ~83% of the entries.\n\n```\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n def all_distances(n, edges):\n D = [[10 ** 5] * n for _ in range(n)]\n for u, v in edges:\n D[u-1][v-1] = 1\n D[v-1][u-1] = 1\n for v in range(n):\n D[v][v] = 0\n \n for k in range(n):\n for i in range(n):\n for j in range(n):\n D[i][j] = min(D[i][j], D[i][k] + D[k][j])\n return D\n \n def make_graph(n, edges):\n G = [[] for _ in range(n)]\n for u, v in edges:\n G[u-1].append(v-1)\n G[v-1].append(u-1)\n return G\n \n def check_connected(G, include):\n if not any(include):\n return False\n root = include.index(True)\n visited = [False] * len(G)\n q = deque([root])\n visited[root] = True\n while q:\n v = q.popleft()\n for x in G[v]:\n if not visited[x] and include[x]:\n visited[x] = True\n q.append(x)\n return visited == include\n \n def max_distance(D, include):\n m = 0\n for i in range(n):\n if include[i]:\n for j in range(i, n):\n if include[j]:\n m = max(m, D[i][j])\n return m\n \n def rec(include, idx, ans, G, D):\n if idx == n:\n if check_connected(G, include):\n d = max_distance(D, include)\n if d >= 1:\n ans[d-1] += 1\n else:\n rec(include, idx + 1, ans, G, D)\n include[idx] = True\n rec(include, idx + 1, ans, G, D)\n include[idx] = False\n\n G = make_graph(n, edges)\n D = all_distances(n, edges)\n include = [False] * n\n ans = [0] * (n-1)\n \n rec(include, 0, ans, G, D)\n\n return ans\n```
5
0
[]
0
count-subtrees-with-max-distance-between-cities
C++ | Best Code | Best Explanation
c-best-code-best-explanation-by-ujjawalk-dr6f
Short Explanation\n For all subsets check:\n\t If it is valid subtree or not ?\n\t\t If it is valid subtree then find the maximum distance between two nodes.\n\
UjjawalKumar29101999
NORMAL
2020-10-11T11:52:26.866610+00:00
2020-10-11T17:08:18.938834+00:00
396
false
**Short Explanation**\n* For all subsets check:\n\t* If it is valid subtree or not ?\n\t\t* If it is valid subtree then find the maximum distance between two nodes.\n\t\t* Let ```ans[n-1]``` is the return vector and let maximum distance be ```dist```, then add one to ```ans[dist-1]``` (Because it is now 1-based indexing). \n\n\n**Detailed Explanation**\n* Created adjacency matrix named ```vector<vector<int>>adj``` using function ```makeAdjMatrix()```.\n* Used function ```preComputeDist()``` (Floyd Warshall Algorithm) to calculate shortest distance from each node to each other node and stored it in ```vector<vector<int>>dist```.\n* Then I generated all subsets using bit manipulation and for every subset:\n\t* If the size of subset is greater than 1 and it is ```validSubtree```\n\t\t* I calculated maximum distance in that subtree by checking distance of each node with each other node.\n\n**Checking the subtree validity of given subset**\n* Create a ```vis[n+1]``` array. \n\t* ```vis[i]=0``` means ```ith``` node is not present in subset.\n\t* ```vis[i]=1``` means ```ith``` node is present in subset.\n\t* ```vis[i]=2``` means ```ith``` node is visited when doing ```dfs``` on the subtree.\n* We do dfs from any node given in subset, and we only traverse further to neighbouring node if that node is present in given subset. And we stop when we don\'t have any options left.\n* Using above method, if the subset is valid, all the ```ith``` nodes that has initially ```vis[i]==1``` will now have ```vis[i]==2```. And hence the summation of all the elements in ```vis[]``` will become ```2*size of provided subset```. Then we will return true, else we will return false.\n\n```\nclass Solution {\nprivate:\n vector<vector<int>>dist;\n vector<vector<int>>adj;\n \n\t/*\n\tFloyd Warshall method to calculate shortest distance \n\tfrom each node to each other node.\n\t@params int n\n\t@params vector<vector<int>>edges\n\t@return void\n\t*/\n void preComputeDist(int n, vector<vector<int>>edges){\n dist = vector<vector<int>>(n+1,vector<int>(n+1,INT_MAX));\n for(auto v:edges){\n dist[v[0]][v[1]]=1;\n dist[v[1]][v[0]]=1;\n } \n \n for(int k=1;k<=n;k++){\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n if(i==j){\n dist[i][j]=0;\n }else{\n if(dist[i][k]!=INT_MAX && dist[k][j]!=INT_MAX){\n dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);\n }\n }\n }\n }\n }\n \n return;\n }\n \n\t/*\n\tFinds distance from each node of set,\n\tto each other node of set and \n\treturns the maximum of all distance\n\t@params set<int>s\n\t@return int\n\t*/\n int maxDist(set<int>s){\n int ans=0;\n for(auto it1:s){\n for(auto it2:s){\n ans = max(ans,dist[it1][it2]);\n }\n }\n return ans;\n }\n \n\t/*\n\tCreates adjacency matrix from the given edges.\n\t@params int n\n\t@params vector<vector<int>>edges\n\t@return void\n\t*/\n void makeAdjMatrix(int n, vector<vector<int>>edges){\n adj = vector<vector<int>>(n+1);\n for(auto v:edges){\n adj[v[0]].push_back(v[1]);\n adj[v[1]].push_back(v[0]);\n }\n return;\n }\n \n\t/*\n\t@params int node\n\t@params int par\n\t@params int[] vis\n\t@return void\n\t*/\n void dfs(int node, int par, int *vis){\n for(auto it:adj[node]){\n if(it!=par && vis[it]){\n vis[it]=2;\n dfs(it, node, vis);\n }\n }\n }\n \n\t/*\n\tFor a given subset, it returns true if the subset is\n\tvalid subtree or not.\n\t@params int n\n\t@params set<int>s\n\t@return bool\n\t*/\n bool validSubtree(int n, set<int>s){\n int start = *s.begin();\n int vis[n+1];\n memset(vis,0,sizeof(vis));\n for(auto it:s){\n vis[it]=1;\n }\n vis[start]=2;\n dfs(start, -1, vis);\n int cnt=0;\n for(int i=1;i<=n;i++)cnt+=vis[i];\n if(cnt==2*s.size())return true;\n return false;\n }\n \npublic:\n\n\t/*\n\t@params int n\n\t@params vector<vector<int>>edges\n\t@return vector<int>\n\t*/\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<int>ans(n-1);\n \n\t\t//create adj matrix\n makeAdjMatrix(n,edges);\n\t\t\n\t\t//store shortes dist from each \n\t\t//node to each other node\n preComputeDist(n,edges);\n \n\t\t//generate all subsets.\n for(int i=0;i<(1<<n);i++){\n set<int>s;\n for(int j=0;j<n;j++){\n if(i&(1<<j)){\n s.insert(j+1);\n }\n }\n\t\t\t\n\t\t\t//for each generated subsets,\n\t\t\t//check if it is valid subset or not.\n if(s.size()>1 && validSubtree(n,s)){\n\t\t\t\n\t\t\t\t//find the maximum distance (Maximum diameter)\n\t\t\t\t//of the subset.\n int dist = maxDist(s);\n ans[dist-1]++;\n }\n }\n \n return ans;\n }\n};\n```
5
1
['Depth-First Search', 'C', 'Bitmask']
1
count-subtrees-with-max-distance-between-cities
[python] Dynamic Programming, O(2^N*N)
python-dynamic-programming-o2nn-by-nate1-o3fl
First calculate all node pairs\' distances, and then iterate all possible states sequentially while each state only require one update, therefore time complexit
nate17
NORMAL
2020-10-11T08:18:34.619721+00:00
2020-10-12T03:12:28.441548+00:00
531
false
First calculate all node pairs\' distances, and then iterate all possible states sequentially while each state only require one update, therefore time complexity is only O(2^N*N)\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n res = [0]*(n-1)\n g = defaultdict(list)\n gs = [0]*n\n dp = [0]*(1<<n)\n for a, b in edges:\n a -= 1\n b -= 1\n g[a].append(b)\n g[b].append(a)\n gs[a] |= (1<<b)\n gs[b] |= (1<<a)\n dp[(1<<a)|(1<<b)] = 1\n dis = [[0]*n for _ in range(n)]\n def dfs(root, cur, depth, parent):\n dis[root][cur] = depth\n for nxt in g[cur]:\n if nxt == parent:\n continue\n dfs(root, nxt, depth+1, cur)\n return\n\n for i in range(n):\n dfs(i,i,0,-1)\n \n# print(dis)\n# print(ees)\n \n for state in range(1<<n):\n # print(state, dp[state])\n if dp[state] > 0:\n res[dp[state]-1] += 1\n for i in range(n):\n if dp[state | (1<<i)] == 0 and (state & gs[i]):\n dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if dp[state | (1<<i)] == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if state & (1<<i) == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state ^ (1<<i)] = max(dp[state ^ (1<<i)], dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n return res\n\n```
4
0
['Dynamic Programming', 'Bitmask', 'Python3']
0
count-subtrees-with-max-distance-between-cities
just found this question can use dp and O(n^5)?
just-found-this-question-can-use-dp-and-48tau
following code is from other guys, it passed using just 16ms\nand I think dp[x][k][y] is degree from x to y as k is intermediary node. I guess\nO(n^5) is just m
0xffffffff
NORMAL
2020-10-11T04:30:55.805261+00:00
2020-10-11T04:43:43.021010+00:00
585
false
following code is from other guys, it passed using just 16ms\nand I think dp[x][k][y] is degree from x to y as k is intermediary node. I guess\nO(n^5) is just my guess, still digesting the code\nBTW my code takes about 520ms and I know why I cannot get Google offer, LOL.\n\n```\n#define _CRT_SECURE_NO_WARNINGS\n#define _USE_MATH_DEFINES\n#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS\n#pragma GCC target("avx2")\n#pragma GCC optimize("O3")\n#pragma GCC optimize("unroll-loops")\n#pragma comment (linker, "/STACK:526000000")\n#include "bits/stdc++.h"\nusing namespace std;\ntypedef string::const_iterator State;\n#define eps 1e-8L\n#define MAX_MOD 1000000007LL\n#define GYAKU 500000004LL\n#define MOD 998244353LL\n#define pb push_back\n#define mp make_pair\ntypedef long long ll;\ntypedef long double ld;\n#define REP(a,b) for(long long (a) = 0;(a) < (b);++(a))\n#define ALL(x) (x).begin(),(x).end()\nunsigned long xor128() {\n\tstatic unsigned long x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n\tunsigned long t = (x ^ (x << 11));\n\tx = y; y = z; z = w;\n\treturn (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));\n};\n\nclass Solution {\npublic:\n\tvector<int> vertexs[30];\n\tint used[30] = {};\n\tint sizing[30] = {};\n\tint dp[30][30][30];\n\tvoid dfs(int now, int back) {\n\t\tvector<int> can_go;\n\t\tsizing[now] = 1;\n\t\tfor (auto& x : vertexs[now]) {\n\t\t\tif (x == back or used[x]) continue;\n\t\t\tdfs(x, now);\n\t\t\tcan_go.push_back(x);\n\t\t}\n\t\tREP(i, 30) {\n\t\t\tREP(q, 30) {\n\t\t\t\tdp[now][i][q] = 0;\n\t\t\t}\n\t\t}\n\t\tfor (auto& x : can_go) {\n\t\t\tint cnts[30][30] = {};\n\t\t\tREP(j, sizing[x] + 1) {\n\t\t\t\tREP(t, sizing[x] + 1) {\n\t\t\t\t\tcnts[j + 1][max(t, j + 1LL)] += dp[x][j][t];\n\t\t\t\t}\n\t\t\t}\n\t\t\tREP(i, sizing[now]) {\n\t\t\t\tREP(q, sizing[now]) {\n\t\t\t\t\tcnts[i][q] += dp[now][i][q];\n\t\t\t\t}\n\t\t\t}\n\t\t\tREP(i, sizing[now]) {\n\t\t\t\tREP(q, sizing[now]) {\n\t\t\t\t\tif (dp[now][i][q] == 0) continue;\n\t\t\t\t\tREP(j, sizing[x]) {\n\t\t\t\t\t\tREP(t, sizing[x]) {\n\t\t\t\t\t\t\tint rights = max({ q,t,i + j + 1 });\n\t\t\t\t\t\t\tif (rights < 30)\n\t\t\t\t\t\t\t\tcnts[max(i, j + 1)][rights] += dp[now][i][q] * dp[x][j][t];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswap(cnts, dp[now]);\n\t\t\tsizing[now] += sizing[x];\n\t\t}\n\t\tdp[now][0][0] = 1;\n\t\treturn;\n\t}\n\tvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n\t\tREP(i, n) {\n\t\t\tvertexs[i].clear();\n\t\t\tused[i] = 0;\n\t\t}\n\t\tREP(i, edges.size()) {\n\t\t\tedges[i][0]--;\n\t\t\tedges[i][1]--;\n\t\t\tvertexs[edges[i][0]].push_back(edges[i][1]);\n\t\t\tvertexs[edges[i][1]].push_back(edges[i][0]);\n\t\t}\n\t\tvector<int> ans(n - 1, 0);\n\t\tREP(i, n) {\n\t\t\tdfs(i, -1);\n\t\t\tused[i] = 1;\n\t\t\tREP(q, 30) {\n\t\t\t\tREP(j, n - 1) {\n\t\t\t\t\tans[j] += dp[i][q][j + 1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n};\n```\n\n
4
0
[]
4
count-subtrees-with-max-distance-between-cities
c++ | easy | short
c-easy-short-by-venomhighs7-k158
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> g(n, vec
venomhighs7
NORMAL
2022-10-27T03:05:17.881444+00:00
2022-10-27T03:05:17.881491+00:00
1,013
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> g(n, vector<int>(n, 999));\n for (auto &e : edges) {\n int i = e[0] - 1;\n int j = e[1] - 1;\n g[i][j] = g[j][i] = 1;\n }\n \n for (int k = 0; k < n; k++) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n g[i][j] = min(g[i][j], g[i][k] + g[k][j]);\n }\n }\n }\n \n vector<int> ans(n - 1, 0);\n for (int s = 0; s < (1 << n); s++) {\n int k = __builtin_popcount(s);\n int e = 0;\n int d = 0;\n for (int i = 0; i < n; i++) if (s & (1 << i)) {\n for (int j = i + 1; j < n; j++) if (s & (1 << j)) {\n e += g[i][j] == 1;\n d = max(d, g[i][j]);\n }\n }\n if (e == k - 1 && d > 0) {\n ans[d - 1]++;\n }\n }\n \n return ans;\n }\n};\n```
3
0
['C++']
1
count-subtrees-with-max-distance-between-cities
[C++] Faster than 100%, 8ms, No Bit Operations, Generate Subtrees Recursively
c-faster-than-100-8ms-no-bit-operations-pnm33
Rather than using a bitmask, we recursively generate all subtrees of a child and then use another recursion to generate all possible trees using any combination
zed_b
NORMAL
2020-10-13T10:48:43.463730+00:00
2020-10-13T18:33:10.080262+00:00
506
false
Rather than using a bitmask, we recursively generate all subtrees of a child and then use another recursion to generate all possible trees using any combination of those subtrees. For each tree, we actually only need it\'s height and it\'s diameter.\nIt\'s slightly harder to code than the other approach of bitmask + tree diameter, but at least you don\'t need the O(N) diamater algorithm.\n\nTime: O(#subtrees * N) , so if it\'s a line it\'s O(N^3), if it\'s a star it\'s O(2^N * N)\n\n```C++\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n struct subtree {\n int height;\n int diameter;\n };\n vector<int> res(n-1, 0);\n vector<vector<int>> adj(n);\n for (auto e : edges) {\n adj[e[0]-1].push_back(e[1]-1);\n adj[e[1]-1].push_back(e[0]-1);\n }\n function<vector<subtree>(int, int)> dfs = [&](int u, int par) {\n vector<vector<subtree>> children;\n for (int v : adj[u]) {\n if (v == par) continue;\n children.push_back(dfs(v, u));\n }\n vector<subtree> trees;\n int at = 0;\n function<void(int,int,int,int)> generateTrees = [&](int at, int max_height1, int max_height2, int diam) {\n if (at == children.size()) {\n\t\t\t\t // generate new tree based on max_heights and biggest diameter of all used subtrees\n int h,d;\n if (max_height1 < 0) {\n h = 0;\n d = 0;\n } else if (max_height2 < 0) {\n h = max_height1 + 1;\n d = max(diam, max_height1 + 1);\n } else {\n h = max_height1 + 1;\n d = max(diam, max_height1 + max_height2 + 2);\n }\n if (d > 0) {\n res[d-1]++;\n }\n trees.push_back({h,d});\n } else {\n for (int i = 0; i <= children[at].size(); i++) {\n if (i == children[at].size()) {\n\t\t\t\t\t\t // decide not to use any of this child\'s subtrees\n generateTrees(at+1, max_height1, max_height2, diam);\n } else {\n\t\t\t\t\t\t // decide to use subtree i of this child\n int h = children[at][i].height;\n int d = children[at][i].diameter;\n int mh1 = max_height1;\n int mh2 = max_height2;\n if (h > mh1) {\n mh2 = mh1;\n mh1 = h;\n } else if (h > mh2) {\n mh2 = h;\n } \n generateTrees(at+1, mh1, mh2, max(diam, d));\n }\n }\n }\n };\n generateTrees(0, -1, -1, -1);\n return trees;\n };\n dfs(0, -1);\n return res;\n }\n};\n\n```
3
0
[]
1
count-subtrees-with-max-distance-between-cities
Brute force checking all subgraphs with neat bfs trick to find diameter
brute-force-checking-all-subgraphs-with-29ll9
The solution consists of the following steps:\n1. Use bit-masking to generate all possible subgraphs\n2. For each subgraph, bfs to check if it is connected (and
yuhan-wang
NORMAL
2020-10-11T04:36:42.309035+00:00
2020-10-11T04:51:26.182503+00:00
698
false
The solution consists of the following steps:\n1. Use bit-masking to generate all possible subgraphs\n2. For each subgraph, `bfs` to check if it is connected (and therefore a subtree); \n3. For each subtree, do a `bfs` again to compute its diameter.\n\nThe way I compute the diameter is based on the following theorem:\nFor any given node `a` of the tree, a farthest node `b` from `a` must be one of the end points of a path with maximal length. i.e. there exists a path from `b` to `c` whose length is maximal. \nUsing this fact, when we do the first `bfs` with a random root, we find `b`. Then we do another `bfs` with `b` as the root to find `c` and the corresponding diameter of the tree. \n\nBelow are my codes:\n\n```\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n graph = collections.defaultdict(list)\n for a, b in edges:\n graph[a-1] += [b-1]\n graph[b-1] += [a-1]\n \n def bfs(root, nodes, k):\n s = [root]\n seen = set(s)\n d = -1\n while s:\n d += 1\n new_s = []\n for node in s:\n new_s += [x for x in graph[node] if (1 << x) & nodes and x not in seen]\n if not new_s:\n far = s[0]\n s = new_s\n seen = seen.union(new_s)\n if len(seen) != k:\n return root, float("inf")\n return far, d\n def find(nodes):\n i = next(i for i in range(n) if (1 << i) & nodes)\n k = bin(nodes).count("1")\n far, d = bfs(i, nodes, k)\n if d == float("inf"):\n return 0\n _, d = bfs(far, nodes, k)\n return d\n ans = [0]*n\n for i in range(1, 1 << n):\n ans[find(i) - 1] += 1\n ans.pop()\n return ans\n```\nTime Complexity: `O(n*2^n)`
3
0
['Breadth-First Search', 'Bitmask']
1
count-subtrees-with-max-distance-between-cities
[Python] EASY to Understand Try All Subsets with Comments
python-easy-to-understand-try-all-subset-mo6j
\nclass Solution(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n """\n :type n: int\n :type edges: List[List[int]]\n
tomzy
NORMAL
2020-10-11T04:15:27.524401+00:00
2020-10-11T04:18:14.892664+00:00
383
false
```\nclass Solution(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n """\n :type n: int\n :type edges: List[List[int]]\n :rtype: List[int]\n """\n import collections\n g = collections.defaultdict(set)\n\t\t# build graph\n for e in edges:\n g[e[0]].add(e[1])\n g[e[1]].add(e[0])\n\t\t\n\t\t# fetch all subsets\n def allset(s):\n x = len(s)\n res = []\n for i in range(1 << x):\n res.append(set(s[j] for j in range(x) if (i & (1 << j))))\n return res\n\t\t\n\t\t# function to find max distance, return value is max distance from cur node to any leaf\n def dfs(cur, d, par):\n if not cur or cur not in d:\n return 0\n self.visited.add(cur)\n res = 0\n ds = [dfs(nei, d, cur) + 1 for nei in g[cur] if nei != cur and nei != par and nei in d]\n if ds:\n\t\t\t\t# update return value first\n res = max(res, max(ds))\n\t\t\t# update global max\n self.max_d = max(self.max_d, res)\n if len(ds) >= 2:\n ds.sort()\n\t\t\t\t# global max could also be two child paths connected by cur node\n self.max_d = max(self.max_d, ds[-1] + ds[-2])\n return res\n\n res = [0 for i in range(1, n)]\n for d in allset([i for i in range(1, n + 1)]):\n self.max_d = 0\n self.visited = set()\n for k in d:\n self.visited.add(k)\n dfs(k, d, None)\n break\n\t\t\t# subset need to be connected\n if self.max_d >= 1 and len(self.visited) == len(d):\n res[self.max_d - 1] += 1\n return res\n \n```
3
0
[]
1
count-subtrees-with-max-distance-between-cities
O(n^3) algorithm
on3-algorithm-by-bangyewu-agww
Intuition\n Describe your first thoughts on how to solve this problem. \nA (sub)tree may have many diameters, but there is exactly one or two centers. To simplf
bangyewu
NORMAL
2023-06-18T07:09:27.199871+00:00
2023-06-18T07:09:27.199898+00:00
99
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA (sub)tree may have many diameters, but there is exactly one or two centers. To simplfying the implementation, we divide into two cases: diameter is even or odd. For the case of even diameter, we count the subtrees by enumerating each vertex as the center. For the case of odd diameter, we enumerate each edge as the center. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each node $v$ as the center, we root the tree at $v$ and do a DFS. When visiting a vertex $u$, we recursively compute the number of subtrees rooted at $u$ and with depth $i$, for each possible $i$.\nWhen combining the results from the children of $u$, a naive implementation takes $O(deg(u)\\times n^2)$ time. By using prefix sum, it can be reduced to $O(deg(u)\\times n)$ time. Thus a DFS takes $O(n^2)$ since the total degree of a tree is $O(n)$.\nAt root $v$, we combine the results from its children. Since we care about only even diameter and centered at $v$, two branches of same depth $i$ form a subtree of diamter $2i$. When combining the branches one by one, we need to count the way that a current subtree is merged with a small incoming subtree which does not change its diameter.\nThe case of odd diameter is similar and simpler since there are only two branches for each center edge.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n^3)$ since each center vertex takes $O(n^2)$.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nLinear.\n\n# Code\n```\nclass Solution:\n # odd/even diameter couned individually\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n adj = [[] for i in range(n)]\n for u,v in edges:\n adj[u-1].append(v-1)\n adj[v-1].append(u-1)\n def comb(p,q): # merge p and q, res[max(i,j)]+=p[i]*q[j]\n if len(q)<len(p): p,q = q,p\n res = [0]*len(q)\n res[0] = p[0]*q[0]\n for i in range(1,len(p)): p[i] += p[i-1]\n for i in range(1,len(q)): q[i] += q[i-1]\n for i in range(1,len(p)):\n res[i] = p[i]*q[i]-p[i-1]*q[i-1]\n for i in range(len(p),len(q)):\n res[i] = (q[i]-q[i-1])*p[-1]\n return res\n \n def dfs(r,p): # num of subtree rooted at r with given depth\n d = [1]\n for v in adj[r]:\n if v==p: continue\n t = [1]+dfs(v,r)\n d = comb(t,d)\n return d\n #end dfs\n ans = [0]*n\n # odd diameter with (u,v) as center edge\n for u,v in edges:\n u -= 1; v-=1\n p = dfs(u,v)\n q = dfs(v,u)\n for i in range(min(len(p),len(q))):\n ans[i+i+1] += p[i]*q[i]\n #even diamter with v as center vertex\n for v in range(n): \n if len(adj[v])==1: continue \n tree = [1]+dfs(adj[v][0],v) #tree with depth\n curr = [0]*n\n for u in adj[v][1:]:\n q = [1]+dfs(u,v)\n # curr tree + new small\n j = 1; t = q[1]+1 # prefix sum of q\n for i in range(4,n,2):\n while j+1<min(i//2,len(q)):\n j += 1; t += q[j]\n curr[i] *= t\n # curr tree + same height\n for i in range(min(len(tree),len(q))):\n curr[i+i] += tree[i]*q[i]\n tree = comb(tree,q)\n for i in range(2,n,2):\n ans[i] += curr[i]\n #end\n return ans[1:]\n\n\n```\n
2
0
['Python3']
1
count-subtrees-with-max-distance-between-cities
Java backtracking
java-backtracking-by-mpettina-14hu
Intuition\n Describe your first thoughts on how to solve this problem. \nFinding the longest path in a tree is a common problem, however this problem requires y
mpettina
NORMAL
2023-01-08T12:43:00.225168+00:00
2023-01-08T12:43:00.225214+00:00
382
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFinding the longest path in a tree is a common problem, however this problem requires you to compute it for all subtrees. From the definition a subtree is essentially a subset of paths in the tree, with the restriction that all paths needs to be connected. For this reason the number of subtrees is likely exponential. \n\nYou can easily prove that solving for the rooted tree is the same as solving the original problem (all paths {A, ..., ROOT, ..., B} can be written as {ROOT, ..., A} + {ROOT, ..., B} as the order doesn\'t matter).\n\nTo generate all subtrees we can just write a backtracking algorithm where in the decision tree we try to append an edge or not to the current path. Then, the key idea is to recurse on the edges rather than the nodes as you normally would, because the edges is where the decision tree forks.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe need to make a recursive call to all edges. For this reason we cannot implement a DFS like algorithm because if we skip the current edge we still need to recurse on the remaining connected edges. The solution is then to design a BFS algorithm where the fronteer expands or reduces according to backtracking.\n\nTo explore only connected edges we can just create adjacency lists.\n\nOnce all edges have been processed the easiest way to find the longest path is to explicitely build the subtree during recursion and once it is done find the longest path on that new tree\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe size of the decision tree. Due to edge connectivity the decision tree is not complete, but we can use the complete decision tree as upper bound.\n\nAll operations in the recursive call take constant time. There is an outer recursion that guesses the root of the subTree, thus recursing n times at most. For each subtree root all possible subtrees are built. Finding the subtree longest path is linear in n.\n$$O(n * 2^(n - 1) * n)$$ = $$O(n^2 * 2^(n - 1))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe height of the decision tree. There is one level per edge. Due to edge connectivity the decision tree is not complete, but we can use the complete decision tree as upper bound. Finding the subtree longest path is linear in n.\n$$O(n - 1 + n)$$ = $$O(n)$$\n\n# Code\n```\nclass Solution {\n\n List<Integer>[] tree, subTree;\n int subTreeRoot, maxPath;\n boolean[] inStack; // do not allow to travel upwards in the rooted tree\n int[] ans;\n\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n buildTree(n, edges);\n ans = new int[n - 1];\n solve(0);\n return ans;\n }\n\n private void buildTree(int n, int[][] edges) {\n tree = new List[n];\n subTree = new List[n];\n inStack = new boolean[n];\n for (int i = 0; i < n; ++i) {\n tree[i] = new ArrayList<>();\n subTree[i] = new ArrayList<>();\n }\n for (int[] e : edges) {\n tree[e[0] - 1].add(e[1] - 1);\n tree[e[1] - 1].add(e[0] - 1);\n }\n }\n\n private void solve(int i) {\n subTreeRoot = i;\n inStack[i] = true;\n buildSubTree(0, 0, Collections.singletonList(i), new ArrayList<>());\n for (int e : tree[i]) {\n if (inStack[e]) {\n continue;\n } \n solve(e);\n }\n }\n\n private void buildSubTree(int i, int j, List<Integer> fronteer, List<Integer> next) {\n if (i >= fronteer.size()) {\n buildNextLevel(next);\n return;\n }\n int curr = fronteer.get(i);\n if (j >= tree[curr].size()) {\n buildSubTree(i + 1, 0, fronteer, next);\n } else {\n int succ = tree[curr].get(j);\n if (inStack[succ]) {\n buildSubTree(i, j + 1, fronteer, next);\n return;\n }\n inStack[succ] = true;\n next.add(succ);\n subTree[curr].add(succ);\n buildSubTree(i, j + 1, fronteer, next);\n next.remove(next.size() - 1);\n subTree[curr].remove(subTree[curr].size() - 1);\n buildSubTree(i, j + 1, fronteer, next);\n inStack[succ] = false;\n }\n }\n\n private void buildNextLevel(List<Integer> next) {\n if (next.isEmpty()) { // subTree is done, add it to the answer\n maxPath = 0;\n computeMaxPath(subTreeRoot);\n if (maxPath > 1) {\n ++ans[maxPath - 2];\n }\n } else {\n buildSubTree(0, 0, next, new ArrayList<>());\n }\n }\n\n private int computeMaxPath(int i) {\n int max = 0, prevMax = 0;\n for (int child : subTree[i]) {\n int h = computeMaxPath(child);\n if (h >= max) {\n prevMax = max;\n max = h;\n } else {\n prevMax = Integer.max(prevMax, h);\n }\n }\n maxPath = Integer.max(maxPath, prevMax + max + 1);\n return max + 1;\n }\n}\n```
2
0
['Java']
0
count-subtrees-with-max-distance-between-cities
Easy to Understand 2 solutions C++ (Time Complexity :O(n^2 * 2^15))
easy-to-understand-2-solutions-c-time-co-ntbr
Solution 1: bit_mask + DFS:\n\nSince the input is small i.e, 15, we can consider n^2 + (n^2) * (2^15)\n\nThis is pretty straightforward\n\n1. Find the distance
pranav_suresh
NORMAL
2022-09-03T12:30:57.992705+00:00
2022-09-03T12:30:57.992737+00:00
319
false
## Solution 1: bit_mask + DFS:\n\nSince the input is small i.e, 15, we can consider n^2 + (n^2) * (2^15)\n\nThis is pretty straightforward\n\n1. Find the distance from node u to all other nodes (O(n^2) complexity)\n2. After setting the distance between node i and node j for all i and j less than < n. \n\n```cpp\nvector<vector<int>> dist_btw_nodes;\n // void setSubtree()\nvoid setDist(int par, int root, int d, vector<vector<int>>& edges, vector<bool> &visited) {\n if (visited[root]){\n return;\n }\n dist_btw_nodes[par][root] = d;\n dist_btw_nodes[root][par] = d;\n visited[root] = true; \n for (int i = 0; i < edges[root].size(); i++) {\n if (edges[root][i] != par) {\n setDist(par, edges[root][i], d + 1, edges, visited);\n }\n }\n return;\n}\n```\n\n1. We have two options either to include the node in the sub-tree or not include the node in the sub-tree. Since the input is 15 we can check all the combinations 2^15. \n\n \n\n```cpp\nvoid dfs(int bit_mask, int index ,int n, vector<int>& ans,vector<int> &vst) {\n if (index > n)return;\n int max_dist = 0;\n int k = __builtin_popcount(bit_mask);\n int set_of_edges_in_subtree = 0;\n\t\t\t\t// Getting the max distance between each node in the subtree\n\t\t\t\t// set_of_edges_in_subtree to check whether the bit_mask/subtree is a\n\t\t\t\t// valid subtree or not, if the number of edge distance 1 isn\'t \n\t\t\t\t// equal to \'number of nodes -1\' then this bit_mask/subtree ain\'t valid. \n for (int i = 0; i < n; i++) {\n if (bit_mask & (1 << i)) {\n for (int j = i + 1; j < n; j++) {\n if (bit_mask & (1<<j)){\n set_of_edges_in_subtree += dist_btw_nodes[i][j] == 1;\n max_dist = max(max_dist, dist_btw_nodes[i][j]);\n }\n }\n }\n }\n if (max_dist > 0 && set_of_edges_in_subtree == (k - 1) && vst[bit_mask] != 1){\n ans[max_dist-1] ++;\n }\n \n vst[bit_mask] = 1;\n dfs(bit_mask ^ (1<<index), index+1, n, ans, vst);\n dfs(bit_mask, index+1, n, ans, vst);\n }\n```\n\n```cpp\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> graph(n+1);\n\t\t\t\t// Creating the graph\n for (int i = 0; i < (n-1); i++){\n graph[edges[i][0]-1].push_back(edges[i][1]-1);\n graph[edges[i][1]-1].push_back(edges[i][0]-1);\n }\n\t\t\n dist_btw_nodes = vector<vector<int>>(n,vector<int>(n,-1));\n\n for (int i = 0; i < n; i++) {\n vector<bool> visited(n, false);\n setDist(i, i, 0, graph, visited);\n }\n vector<int> ans(n-1, 0);\n vector<int> vst(1<<n,-1);\n dfs(0, 0, n, ans, vst);\n return ans;\n }\n```\n\n## Solution 2: Without using DFS (Looping through all the sub trees)\n\nLooping through all the sub trees i.e, from 0 to 2^15.\n\n```cpp\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> graph(n+1);\n for (int i = 0; i < (n-1); i++){\n // cout << edges[i][0]-1 << " " << edges[i][1]-1 << "\\n";\n graph[edges[i][0]-1].push_back(edges[i][1]-1);\n graph[edges[i][1]-1].push_back(edges[i][0]-1);\n }\n dist_btw_nodes = vector<vector<int>>(n,vector<int>(n,-1));\n\n for (int i = 0; i < n; i++) {\n vector<bool> visited(n, false);\n setDist(i, i, 0, graph, visited);\n }\n \n int max_pos_bit_mask = 1 << n;\n vector<int> ans(n-1, 0);\n\n for (int bit_mask = 0; bit_mask <= max_pos_bit_mask; bit_mask++){\n int num_nodes = __builtin_popcount(bit_mask);\n int set_of_edges_in_subtree = 0;\n int max_dist = 0;\n for (int i = 0; i < n; i++) {\n if (bit_mask & (1 << i)) {\n for (int j = i + 1; j < n; j++) {\n if (bit_mask & (1<<j)){\n set_of_edges_in_subtree += dist_btw_nodes[i][j] == 1;\n max_dist = max(max_dist, dist_btw_nodes[i][j]);\n }\n }\n }\n }\n if (max_dist > 0 && set_of_edges_in_subtree == (num_nodes - 1)){\n ans[max_dist-1] ++;\n }\n }\n return ans;\n }\n```
2
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'Bitmask']
0
count-subtrees-with-max-distance-between-cities
Java Solution | Bitmask |
java-solution-bitmask-by-gauravkr442-xeah
\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n \n ArrayList<Integer>[] graph = (ArrayList<
gauravkr442
NORMAL
2022-01-21T12:19:16.767980+00:00
2022-01-21T12:30:32.489722+00:00
296
false
```\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n \n ArrayList<Integer>[] graph = (ArrayList<Integer>[]) new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(int i=0;i<edges.length;i++)\n {\n int u = edges[i][0];\n int v = edges[i][1];\n \n --u;\n --v;\n \n graph[u].add(v);\n graph[v].add(u);\n }\n \n int[] darr = new int[n-1];\n \n for(int mask=0;mask<(1<<(n));mask++)\n {\n int d = getmax(mask , graph);\n \n if(d>0)\n {\n darr[d-1]++;\n }\n }\n \n return darr;\n \n }\n \n int getmax(int mask , ArrayList<Integer>[] graph)\n {\n \n int maxd = -1;\n \n for(int i=0;i<15;i++)\n { \n if( (mask & (1<<i)) !=0)\n {\n maxd = Math.max(maxd , dfs(i , graph , mask));\n }\n }\n \n return maxd;\n }\n \n int dfs(int node , ArrayList<Integer>[] graph , int mask)\n {\n \n \n Queue<Integer> q\n = new LinkedList<>();\n q.add(node);\n int dist = -1;\n int curr = mask;\n \n while(!q.isEmpty())\n {\n dist++;\n \n for(int l=q.size()-1;l>=0;l--) { \n int z1 = q.peek();\n curr = curr ^ (1<<z1);\n q.remove();\n \n for(int z : graph[z1])\n {\n if(((mask & (1<<z))!=0) && ((curr & (1<<z))!=0))\n { \n q.add(z); }\n }\n }\n \n }\n \n if(curr!=0)\n {\n return -1;\n }\n \n return dist;\n \n }\n}\n```
2
0
['Bitmask', 'Java']
0
count-subtrees-with-max-distance-between-cities
Java Bitmask DP
java-bitmask-dp-by-mi1-ei7r
Nice problem combining multiple sub problems. The key ideas are these\n\n1. Enumerate all subtress . There are (1<<n) subtrees , since n is only 15 max this wil
mi1
NORMAL
2021-12-11T09:44:08.332120+00:00
2021-12-11T09:44:08.332148+00:00
139
false
Nice problem combining multiple sub problems. The key ideas are these\n\n1. Enumerate all subtress . There are (1<<n) subtrees , since n is only 15 max this will come to around 33k.\n2. For each subtree check if its valid. \n3. find the max distance between 2 nodes in the subtree essentially the diameter . \n\n```\nclass Solution {\n int farthest = -1;\n int maxDist = -1;\n int pathMask = 0;\n\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n HashMap<Integer, Set<Integer>> graph = new HashMap<>();\n for (int[] edge : edges) {\n edge[0]--;\n edge[1]--;\n Set<Integer> set = graph.getOrDefault(edge[0], new HashSet<>());\n set.add(edge[1]);\n graph.put(edge[0], set);\n set = graph.getOrDefault(edge[1], new HashSet<>());\n set.add(edge[0]);\n graph.put(edge[1], set);\n }\n int[] arr = new int[n];\n for (int i = 1; i <= (1 << n); i++) {\n int aVertex = -1;\n for (int j = 0; j < n; j++) {\n if ((i & (1 << j)) > 0) {\n aVertex = j;\n break;\n }\n }\n if (aVertex != -1) {\n traverse(aVertex, graph, i, 0, 0);\n if (pathMask != -1 && (pathMask ^ i) == 0 && farthest != -1 && maxDist >= 1) {\n //subtree is valid;\n maxDist = -1;\n pathMask = 0;\n traverse(farthest, graph, i, 0, 0);\n arr[maxDist]++;\n }\n }\n pathMask = 0;\n maxDist = -1;\n farthest = -1;\n }\n return Arrays.copyOfRange(arr, 1, arr.length);\n }\n\n private void traverse(int node, HashMap<Integer, Set<Integer>> graph, int subTree, int visited, int nodeDist) {\n pathMask |= (1 << node);\n if (nodeDist > maxDist) {\n maxDist = nodeDist;\n farthest = node;\n }\n if ((visited & (1 << node)) == 0) {\n visited |= (1 << node);\n for (int child : graph.get(node)) {\n if ((visited & (1 << child)) == 0 && ((subTree & (1 << child)) > 0)) {\n traverse(child, graph, subTree, visited, nodeDist + 1);\n }\n }\n }\n }\n}\n```
2
0
[]
0
count-subtrees-with-max-distance-between-cities
[Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained
python-top-down-dp-on5-35-ms-and-faster-46dnk
Idea\n\nI didn\'t see any posted DP solutions with a full writeup (or decent comments), so I wrote out each step in detail. The idea here is to choose any verte
kcsquared
NORMAL
2021-02-16T12:29:08.126426+00:00
2021-09-20T22:01:13.878105+00:00
346
false
**Idea**\n\nI didn\'t see any posted DP solutions with a full writeup (or decent comments), so I wrote out each step in detail. The idea here is to choose any vertex `x` with neighbors `v1,v2...,vk`, and pretend that we have removed each edge `x--vi`. Suppose we only remove the first edge, `x--v1`, to split our tree T into two smaller trees Tx and Tv1 rooted at x and v1. **If we compute diameters and counts for subtrees in `Tx` and `Tv1`, we can \'merge\' these** (i.e. add back the edge `v1`) to find diameters and counts for a combined tree rooted at `x`. We do this merging once for each neighbor, adding back the edge to `v1`, then to `v2` and so on.\n\n**Complexity**\n\nTime: `O(n^5)` We call merge exactly once for each edge; merge is called only from compute_subtree_counts, and compute_subtree_counts is called exactly once for each vertex. There are, worst case, `O(n^4)` operations in merge. Our outer loop in merge is over all (diameter, height) pairs of each subtree of `parent_vertex`, which can be at most `O(n^2)`; the inner loop is also at most `O(n^2)`. In practice, the time complexity is much better than `O(n^5)`, so perhaps it\'s possible to prove a smaller upper bound.\n\nThere may be a way to get `O(n^2)` or `O(n^3)` by using bottom-up DP and precomputing sums in the merge function [as discussed in this post](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/896313/O(n2)-using-DP). If you find an implementation (or even detailed pseudocode) of that idea, please let me know. Space complexity is `O(n^3)` worst case, but I suspect this can be brought down to `O(n^2)` (and I suspect the true value of the current code to already be `O((n^2) log n)`) .\n\n\n**Python**\n\n\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n # Create Tree as adjacency list\n neigh: List[List[int]] = [[] for _ in range(n)]\n for u, v in edges:\n neigh[u - 1].append(v - 1)\n neigh[v - 1].append(u - 1)\n\n distance_array: List[int] = [0] * n\n\n def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int:\n """Given a tree, return a central vertex (minimum radius vertex) with BFS"""\n\n num_neighbors: List[int] = list(map(len, adj_list))\n leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1))\n while len(leaf_nodes) > 1:\n leaf = leaf_nodes.popleft()\n for neighbor in adj_list[leaf]:\n num_neighbors[neighbor] -= 1\n if num_neighbors[neighbor] == 1:\n leaf_nodes.append(neighbor)\n return leaf_nodes[0]\n\n def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int],\n child_subtrees: Dict[Tuple[int, int], int]) -> None:\n\n """ Helper function to merge two disjoint rooted trees T_parent and T_child rooted at \'parent\' and \'child\',\n into one tree rooted at \'parent\', by adding an edge from \'parent\' to \'child\'.\n Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees\n of T_parent that contain \'parent\', have diameter i, and height j.\n Worst case complexity: O(n^4) per call\n """\n\n for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()):\n\n for (diam_for_child, height_for_child), count_from_child in child_subtrees.items():\n\n new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1)\n new_height = max(height_for_parent, height_for_child + 1)\n parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent\n\n return None\n\n def compute_subtree_counts(current_vertex: int,\n last_vertex: int = -1) -> Dict[Tuple[int, int], int]:\n """Recursively counts subtrees rooted at current_vertex using DFS,\n with edge from current_vertex to \'last_vertex\' (parent node) cut off"""\n subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1}\n\n for child_vertex in neigh[current_vertex]:\n if child_vertex == last_vertex:\n continue\n\n merge_into_parent(parent_subtrees=subtree_counts,\n child_subtrees=compute_subtree_counts(current_vertex=child_vertex,\n last_vertex=current_vertex))\n\n for (diameter, height), subtree_count in subtree_counts.items():\n distance_array[diameter] += subtree_count\n\n return subtree_counts\n\n # Optimization: Use a max-degree vertex as our root to minimize recursion depth\n max_degree_vertex: int = find_tree_center(vertices=list(range(n)),\n adj_list=neigh)\n\n compute_subtree_counts(current_vertex=max_degree_vertex)\n\n return distance_array[1:]\n```
2
0
['Dynamic Programming', 'Python3']
1
count-subtrees-with-max-distance-between-cities
[C++] Graph + Bitmask + BFS || 24ms || O(n*n*(2^n))
c-graph-bitmask-bfs-24ms-onn2n-by-am2505-ubxe
Logic:\nAs we form an undirected tree. We can represent a set of cities in bits. \nWe will only consider those set of the city which will be connected and ignor
am2505
NORMAL
2020-10-12T19:17:03.744013+00:00
2020-10-12T19:17:50.084222+00:00
200
false
Logic:\nAs we form an undirected tree. We can represent a set of cities in bits. \nWe will only consider those set of the city which will be connected and ignore non-connected cities.\nAt some position, we take a set of connected cities and represent it in binary as 001101, then we can say city 1, city 3, city 4 are connected and have a value of max distance in that set.\nNow what we want is to add a new city into that set. We can add a new city if we have one node in the current set and the other node (suppose city 2) of edge is not in the current set. Then we can create a new set which is 001111. Finally, we need to find the max distance in this set. There will be a maximum of 2 cases:\n\t1. It will be the same as the current set.\n\t2. If we do a dfs from the new city and visit only those cities which are in curr set.\nFinally, we get the maximum distance in the new set, then we will update it the answer array.\n\nTo work with the set more conveniently, I use the queue data structure in which I initialize it with a singleton set representing each city. Then I take the front set of the queue and then create a new set and push it into the queue.\n\n```\nclass Solution {\npublic:\n vector<list<int>> adjList;\n // finding the max distance from new city inside the curr set of cities\n int dfs(int src, int parent, int mask){\n int maxDist=-1;\n for(auto dest: adjList[src]){\n if(dest == parent) continue;\n if(mask&(1<<dest)) maxDist = max(maxDist, dfs(dest, src, mask));\n }\n return maxDist+1;\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n adjList.resize(n, list<int>()) ;\n for(auto e:edges){\n adjList[e[0]-1].push_back(e[1]-1);\n adjList[e[1]-1].push_back(e[0]-1);\n }\n vector<int> ans(n-1);\n vector<int> memo((1<<n), -1); // will store max distance in set of cities\n queue<int> q;\n for(int i=0; i<n; i++) memo[1<<i]=0, q.push(1<<i);\n while(!q.empty()){\n int currSet = q.front(); q.pop();\n for(int i=0; i<n; i++){\n // considering city which is in curr set\n if(currSet & (1<<i)){\n for(auto d: adjList[i]){ \n if(currSet & (1<<d)) continue;\n int newSet = (currSet|(1<<d));\n if(memo[newSet]>=0) continue;\n // new city doesnot included in set and the new set formed is unvisited\n memo[newSet] = max(memo[currSet], dfs(d, -1, currSet));\n ans[memo[newSet]-1]++;\n q.push(newSet);\n }\n }\n }\n }\n return ans;\n }\n};\n```\n\nTime Complexity: \nO(n * n * (2^n))\nAs we are considering all possible set which will be (2^n) and for each set we are checking all edges which can be formed in that set in n*n .
2
0
['Depth-First Search', 'Breadth-First Search', 'C', 'Bitmask']
0
count-subtrees-with-max-distance-between-cities
[Java] Video Explanation O(n * 2^n)
java-video-explanation-on-2n-by-asher23-llqp
null
asher23
NORMAL
2020-10-12T13:41:03.819333+00:00
2020-10-12T13:41:03.819376+00:00
164
false
<iframe width="560" height="315" src="https://www.youtube.com/embed/XHKA8uIppqY" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
2
0
[]
0
count-subtrees-with-max-distance-between-cities
Java DFS and bitmask
java-dfs-and-bitmask-by-hobiter-xwvt
Reserve\nIntuition:\nConstraints:\n2 <= n <= 15\n\n\n\n
hobiter
NORMAL
2020-10-11T07:01:25.452499+00:00
2020-10-11T07:58:24.664830+00:00
186
false
Reserve\nIntuition:\nConstraints:\n2 <= **n <= 15**\n\n```\n\n```
2
2
[]
2
count-subtrees-with-max-distance-between-cities
[JAVA] O(n*(2^n)) backtracking solution with detailed explanation.
java-on2n-backtracking-solution-with-det-hf9q
Idea: Using backtracking choose which vertex is to be included and which is not. If it forms a valid tree, find the maximum distance between two nodes in it.\n\
pramitb
NORMAL
2020-10-11T04:02:26.281276+00:00
2020-10-11T04:52:45.504695+00:00
555
false
Idea: Using backtracking choose which vertex is to be included and which is not. If it forms a valid tree, find the maximum distance between two nodes in it.\n```\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n boolean []isIncluded=new boolean[n+1]; // to determine which vertex is included in the subset and which is not.\n \n // edge list\n List<List<Integer>> list=new ArrayList<>();\n for(int i=0;i<=n;i++)\n list.add(new ArrayList<>());\n \n // creating the edges\n for(int []e:edges){\n list.get(e[0]).add(e[1]);\n list.get(e[1]).add(e[0]);\n }\n \n int []ans=new int [n-1]; // to store the answer.\n \n helper(1,isIncluded,list,n,ans);\n return ans;\n }\n public void helper(int i, boolean []isIncluded, List<List<Integer>> list, int n, int[] ans){\n // This function selects which vertex is included and which is not, by backtracking.\n \n if(i==n+1){\n int val=find(isIncluded,n,list); // returns -1 if the subtree is not connected or consists of a single vertex or is an empty tree. \n if(val>0)\n ans[val-1]++; \n return;\n }\n \n helper(i+1,isIncluded,list,n,ans); // vertex is not included.\n isIncluded[i]=true;\n helper(i+1,isIncluded,list,n,ans); // vertex is included.\n isIncluded[i]=false; // backtracking step. \n }\n \n int max=0; // to store the max distance between any two nodes.\n public int find(boolean []isIncluded, int n, List<List<Integer>> list){\n int cnt=0,root=-1;\n \n // counting the number of included vertices and choosing the first included vertex as the root(any included vertex can be chosen as the root).\n for(int i=1;i<=n;i++){\n if(isIncluded[i]){\n if(root==-1)\n root=i;\n cnt++;\n }\n }\n \n // if the number of vertices are less than or equal to 1, i.e., either the tree is empty or consists of a single vertex.\n if(cnt<=1)\n return -1;\n \n max=0;// initialising the global variable.\n \n boolean []vis=new boolean[n+1]; // to find every included vertex is reachable or not.\n \n maxDist(root,list,isIncluded,vis); \n \n // to see if any vertex is unreachable from the root.\n for(int i=1;i<=n;i++)\n if(isIncluded[i]&&!vis[i]) // if unreachable, return -1, as the subtree is not connected.\n return -1; \n \n return max; // returning maximum distance between two nodes in the subtree.\n }\n public int maxDist(int i, List<List<Integer>> list, boolean []isIncluded, boolean []vis){\n /*\n first: to store the largest path in the subtree treating the current vertex as the root.\n second: to store the second-largest path in the subtree treating the current vertex as the root.\n */\n int first=0, second=0,val;\n vis[i]=true;\n \n for(int j:list.get(i)){\n if(isIncluded[j]&&!vis[j]){ // we can visit a vertex only if it is included in the current subtree.\n val=maxDist(j,list,isIncluded,vis);\n if(val>first){\n second=first;\n first=val;\n }\n else if(val>second)\n second=val;\n }\n }\n max=Math.max(max,first+second); // updating the max value.\n return first+1;\n }\n}\n// O(n*(2^n)) Time Complexity.\n```\nThanks for reading. Please upvote.
2
0
[]
0
count-subtrees-with-max-distance-between-cities
A clean solution in C (time complexity O(n^3)) | ☺
a-clean-solution-in-c-time-complexity-on-9zut
Complexity Time Complexity: O(n³) - This comes from the nested DFS traversals and combination calculations for each node and edge. Space Complexity: O(n²) -
dub04ek
NORMAL
2025-03-26T22:20:54.707363+00:00
2025-03-26T22:20:54.707363+00:00
19
false
## Complexity - Time Complexity: O(n³) - This comes from the nested DFS traversals and combination calculations for each node and edge. - Space Complexity: O(n²) - We store intermediate results for subtree combinations during the DFS. ## Code Explanation 1. Tree Construction: Builds the adjacency list from input edges. 1. DFS Function: Recursively explores subtrees and calculates the number of nodes at each depth. 1. Combination Function: Merges subtree counts from different child branches. 1. Result Calculation: Aggregates counts for all possible diameters by considering both edge-centered and node-centered cases. # Code ```c [] #define MAX_N 15 #define min(a, b) ((a) < (b) ? (a) : (b)) typedef struct { int size; int data[MAX_N]; } array_t; array_t __adj[MAX_N]; array_t *combinations(array_t *arr1, array_t *arr2) { if (arr1->size > arr2->size) return combinations(arr2, arr1); array_t *ret = calloc(1, sizeof(array_t)); ret->size = arr2->size; ret->data[0] = arr1->data[0] * arr2->data[0]; for (int i = 1; i < arr1->size; ++i) arr1->data[i] += arr1->data[i - 1]; for (int i = 1; i < arr2->size; ++i) arr2->data[i] += arr2->data[i - 1]; for (int i = 1; i < arr1->size; ++i) ret->data[i] = arr1->data[i] * arr2->data[i] - arr1->data[i - 1] * arr2->data[i - 1]; for (int i = arr1->size; i < arr2->size; ++i) ret->data[i] = (arr2->data[i] - arr2->data[i - 1]) * arr1->data[arr1->size - 1]; return ret; } array_t *dfs(int root, int parent) { array_t *ret = malloc(sizeof(array_t)); ret->data[0] = 1; ret->size = 1; array_t *tmp, *combined; for (int i = 0; i < __adj[root].size; ++i) { int node = __adj[root].data[i]; if (node == parent) continue; tmp = dfs(node, root); combined = combinations(tmp, ret); free(tmp); free(ret); ret = combined; } memmove(ret->data + 1, ret->data, ret->size * sizeof(int)); ret->data[0] = 1; ++ret->size; return ret; } int *countSubgraphsForEachDiameter(int n, int** edges, int edges_size, int *, int *ret_size) { for (int i = 0; i < n; ++i) __adj[i].size = 0; for (int i = 0; i < edges_size; ++i) { int u = edges[i][0] - 1, v = edges[i][1] - 1; __adj[u].data[__adj[u].size++] = v; __adj[v].data[__adj[v].size++] = u; } int ans[MAX_N] = { 0 }; for (int i = 0; i < edges_size; ++i) { int u = edges[i][0] - 1, v = edges[i][1] - 1; array_t *u_tree = dfs(u, v), *v_tree = dfs(v, u); int min_len = min(u_tree->size, v_tree->size); for (int j = 1; j < min_len; ++j) ans[(j << 1) - 1] += u_tree->data[j] * v_tree->data[j]; free(u_tree); free(v_tree); } for (int root = 0; root < n; ++root) { if (__adj[root].size == 1) continue; array_t *tree = dfs(__adj[root].data[0], root); int curr[MAX_N] = { 0 }; for (int i = 1; i < __adj[root].size; ++i) { array_t *cur_tree = dfs(__adj[root].data[i], root); int j = 1, prefix = cur_tree->data[1] + 1; for (int k = 4; k < n; k += 2) { while (j + 1 < min(k >> 1, cur_tree->size)) prefix += cur_tree->data[++j]; curr[k] *= prefix; } int min_len = min(tree->size, cur_tree->size); for (int k = 0; k < min_len; ++k) curr[k << 1] += tree->data[k] * cur_tree->data[k]; array_t *tmp = combinations(tree, cur_tree); free(tree); free(cur_tree); tree = tmp; } free(tree); for (int k = 2; k < n; k += 2) ans[k] += curr[k]; } int *ret = malloc((n - 1) * sizeof(int)); *ret_size = n - 1; memcpy(ret, ans + 1, (n - 1) * sizeof(int)); return ret; } ``` ## Attribution This [solution](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/solutions/3651372/o-n-3-algorithm) was inspired by the approach shared by user **bangyewu**.
1
0
['C']
0
count-subtrees-with-max-distance-between-cities
solving using Bitmask
solving-using-bitmask-by-ujjwalbharti13-8y0h
IntuitionApproachComplexity Time complexity: Space complexity: Code
UjjwalBharti13
NORMAL
2025-01-24T05:30:59.680109+00:00
2025-01-24T05:30:59.680109+00:00
51
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: // Approach // first we make all possible subset of tree // And after that find which is valid subset that are connected with eachother with the help of other NODE or itseft // we we got the connected then we traverse through BIt and check binary which is valid subset and filled them it in vector //In solve fundtion we just check the given subtree is valid or not with the help of rightshif&1 int solve(int subtree , vector<vector<int>>&dist , int n){ int cntN = 0 , cntE = 0 , mxd = 0; for(int i = 0 ; i<n; i++){ if(((subtree>>i)&1) == 0)continue; // N:3 E:2 cntN++; for(int j = i+1; j<n; j++){ if(((subtree>>j)&1) == 0)continue; if(dist[i][j] == 1){ cntE++; } mxd = max(mxd,dist[i][j]); } } if(cntN == cntE + 1){ return mxd; } return -1; } // // 0010 // //0001 // 2/2 = 1 // 0001<<1 = 0010 = 2 // 1*2 = 2 vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) { vector<int>v(n-1,0); // number of subtrees for each distance vector<vector<int>>dist(15 , vector<int>(15,INT_MAX)); for(auto temp : edges){ dist[temp[0]-1][temp[1]-1] = 1; dist[temp[1]-1][temp[0]-1] = 1; } for(int k = 0 ; k<n; k++){ for(int i = 0 ; i<n; i++){ for(int j = 0 ; j<n; j++){ if(dist[i][k] == INT_MAX || dist[j][k] == INT_MAX)continue; dist[i][j] = dist[j][i] = min({dist[i][j],dist[j][i],dist[i][k] + dist[k][j]}); } } } // we iterate over all the subsets //0010 //0111 for(int i = 0 ; i<(1<<n); i++){ int ans = solve(i,dist,n); if(ans > 0){ v[ans-1]++; } } return v; } }; ```
1
0
['C++']
0
count-subtrees-with-max-distance-between-cities
easy approach
easy-approach-by-anoopkaurbhullar-oary
\n\n# Code\n```\n\nclass Solution {\npublic:\nvector> g;\n\n // DFS function to compute the maximum depth and update the diameter\n int dfsDepth(int v, int i
Anoopkaurbhullar
NORMAL
2024-07-05T18:28:04.366175+00:00
2024-07-05T18:28:04.366218+00:00
127
false
\n\n# Code\n```\n\nclass Solution {\npublic:\nvector<vector<int>> g;\n\n // DFS function to compute the maximum depth and update the diameter\n int dfsDepth(int v, int i , unordered_set<int> &vis, int &res){\n vis.insert(v);\n int max1=0;\n int max2=0;\n for(auto nei: g[v]){\n if(((1<<nei)&i) && vis.find(nei)==vis.end()){\n int depth=1+dfsDepth(nei,i,vis,res);\n if(depth>max1){\n max2=max1; \n max1=depth;\n }\n //taking two max vaues and resturng the max out of thm\n else if(depth>max2){\n max2=depth;\n }\n }\n }\n res=max(res,max1+max2);\n return max1;\n }\nint f(int i, int startNode) {\n int diameter = 0;\n // Calculate maximum depth and update diameter from startNode\n unordered_set<int> subtree;\n dfsDepth( startNode,i, subtree,diameter);\n return diameter;\n}\n\n // Function to find the first set bit in the binary representation of i\n int frstSetBit(int i, int n) {\n for (int j = 0; j < n; j++) {\n if ((1 << j) & i) { // if bit j is set\n return j;\n }\n }\n return -1; // No set bit found\n }\n\nbool validSubtree(int i, int n, int firstSetBit, int& mask) {\n\n mask|=(1<<firstSetBit);\n if (mask == i )\n return true;\n\n for (auto p : g[firstSetBit]) {\n if ((i & (1 << p)) && !(mask & (1 << p))) { // twon thinf tocheck , valid tree part,and prev visisted\n if(validSubtree(i, n, p,mask))\n return true;\n }\n }\n return false;\n} \n\n\n\n vector<int> countSubgraphsForEachDiameter(int n, std::vector<std::vector<int>>& edges) {\n g.resize(n);\n std::vector<int> ans(n-1, 0);\n\n // Build the graph\n for (auto p : edges) {\n g[p[0] - 1].push_back(p[1] - 1);\n g[p[1] - 1].push_back(p[0] - 1);\n }\n\n // Iterate over all possible subtrees represented by bitmasks\n for (int i = 1; i < (1 << n); i++) { int firstSetBit = frstSetBit(i, n);\nint o=0;\n if (validSubtree(i, n,firstSetBit,o))// if this is a valid subtree, then find the largest diameter of this tree\n {\n int diameter = f(i, firstSetBit);\n if (diameter > 0 && diameter < n) {\n ans[diameter - 1]++;\n }\n }\n }\n\n return ans;\n }\n};
1
0
['Bit Manipulation', 'Depth-First Search', 'Bitmask', 'C++']
1
count-subtrees-with-max-distance-between-cities
Beat 100% | O(n^3) | DP | BFS + DFS | Iterate diameters | Explained
beat-100-on3-dp-bfs-dfs-iterate-diameter-dsh7
Intuition\n Describe your first thoughts on how to solve this problem. \nVery hard. My respect for those who come up with this approach.\n \n# Approach\n Descr
narfuls
NORMAL
2023-10-13T18:50:44.334484+00:00
2023-10-13T18:50:44.334511+00:00
54
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVery hard. My respect for those who come up with this approach.\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we need to know neighbors for each city, so create an adjacency list.\nNext we need to know distance between any two cities. Create 2d array distances using BFS.\n\n**Main idea:**\nFor every pair of cites calculate number subtrees between, such that maximum distance in subtree less or equal diameter.\n![example](https://assets.leetcode.com/uploads/2020/09/21/p1.png)\nTake **1 and 2 as diameter**. There is only one subtree because distance from 3 or 4 to 1 is more than the diameter.\nLet\'s take **1 and 3 as diameter**. How many subtrees between 1 and 3? There are two subtrees (we have to choose 2, but 4 is optional).\nWe can use DFS to calculate number of subtrees. \nStart from 1 look for adjacent.\nDistance from 2 to 1 plus distance from 2 to 3 equals the diameter, so we have to choose 2.\nDistance from 4 to 1 plus distance from 4 to 3 more than the diameter, so 4 is optional. Multiply number subtrees by 2.\nHowever, if we take **1 and 4 as diameter** we count full tree twice. How to avoid such situation? We can iterate cities in increasing order and when distance to any diameter edge equals the diameter choose city only if it is greater than other edge.\nDistance from 1 to 3 is equal the diameter, but 3 less than 4 so we cannot choose 3.\n\n**More complex example:**\n![example](https://raw.githubusercontent.com/narfuls/leet-image/main/Diameter.PNG)\n3 and 8 edges of diameter (d=4)\n```\ndist[5][3] + dist[5][8] == d\ndist[1][3] + dist[1][8] == d \ndist[10][3] + dist[10][8] == d\n```\nWe have to choose cities 5, 1 and 10. \n```\ndist[13][3] > d\ndist[14][8] > d\n```\nWe cannot choose cities 13 and 14. \n```\ndist[4][3] == d but 4 < 8\ndist[6][3] == d but 6 < 8\n```\nWe cannot choose cities 4 and 6. \n```\ndist[7][8] == d and 7 > 3\ndist[9][3] == d and 9 > 8\ndist[12][3] == d and 12 > 8\n```\nWe may choose or not to choose cities 7,9 and 12. \n```\ndist[2][3] < d and dist[2][8] < d\ndist[11][3] < d and dist[11][8] < d\n```\nWe may choose or not to choose cities 2 and 11. \n\n**DFS addition value is 0** for required(1, 5 and 10).\n**DFS addition value is 1** for optional(2, 7, 9, 11 and 12)\nForbidden(4, 6,13 and 14) shold be excluded from DFS.\n\n**Number of subtrees between 3 and 8 is DFS(3)**\n```\nDFS(3) == 0 + DFS(5)\nDFS(5) == 0 + DFS(7) * DFS(1)\nDFS(7) == 1 + 1\nDFS(1) == 0 + DFS(2) * DFS(10) * DFS(11)\nDFS(2) == 1 + DFS(9)\nDFS(9) == 1 + 1\nDFS(10) == 0 + 1 // 6 and 8 is forbidden\nDFS(11) == 1 + DFS(12)\nDFS(12) == 1 + 1\n```\n# Complexity\n- Time complexity: O(n^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n private byte[][] dist;\n private List<byte>[] adj;\n private void InitAdjecency(int n, int[][] edges)\n {\n adj = Enumerable.Repeat(0, n).Select(_ => new List<byte>()).ToArray();\n foreach (var edge in edges)\n {\n adj[edge[0] - 1].Add((byte)(edge[1] - 1));\n adj[edge[1] - 1].Add((byte)(edge[0] - 1));\n }\n\n }\n private void DistanceBFS(byte[] disI, byte cur, byte prev)\n {\n foreach (byte next in adj[cur])\n {\n if (next != prev)\n {\n disI[next] = disI[cur]; \n disI[next]++;\n DistanceBFS(disI, next, cur);\n }\n }\n }\n private void InitDistance(int n)\n {\n dist = new byte[n][];\n for (byte i = 0; i < n; i++)\n {\n dist[i] = new byte[n];\n DistanceBFS(dist[i], i, i);\n }\n }\n private int DFS(byte i, byte j, byte cur, byte prev)\n {\n int optionalValue = dist[i][cur] + dist[j][cur] > dist[i][j] ? 1 : 0;\n int res = 1;\n foreach (byte next in adj[cur])\n {\n if (next != prev &&\n (dist[i][next] < dist[i][j] || dist[i][next] == dist[i][j] && next > j) &&\n (dist[j][next] < dist[i][j] || dist[j][next] == dist[i][j] && next > i)) \n res *= DFS(i, j, next, cur);\n }\n return res + optionalValue;\n }\n public int[] CountSubgraphsForEachDiameter(int n, int[][] edges)\n {\n InitAdjecency(n, edges);\n InitDistance(n);\n var res = new int[n-1];\n res[0] = n - 1;\n for (byte i = 0; i < n; i++)\n {\n for (byte j = (byte)(i + 1); j < n; j++)\n {\n if(dist[i][j] > 1)\n res[dist[i][j] - 1] += DFS(i, j, i, 255);\n }\n }\n return res;\n }\n}\n```
1
0
['Dynamic Programming', 'C#']
0
count-subtrees-with-max-distance-between-cities
C++ && Bitmask && DFS Solution
c-bitmask-dfs-solution-by-keviv4-sn0h
Intuition\nSince the constraints are pretty small (n<=15) we can surely think of bitmask.\n# Approach\nTry all possible subtrees using bitmask.\ncheck if it a v
Keviv4_
NORMAL
2023-09-10T19:45:08.754561+00:00
2023-09-10T19:45:08.754595+00:00
44
false
# Intuition\nSince the constraints are pretty small (n<=15) we can surely think of bitmask.\n# Approach\nTry all possible subtrees using bitmask.\ncheck if it a valid subtree.\nthen find maxDis for each valid subtree.\n\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int curr, int prev, int d, vector<int> adj[], int &maxinode, int &ans){\n if (d > ans){\n ans = d;\n maxinode = curr;\n }\n for (auto i : adj[curr]){\n if (i != prev){\n dfs(i, curr, d + 1, adj, maxinode, ans);\n }\n }\n }\n void dfs(int node,int prev,vector<int>adj2[],int &mask2){\n mask2=(mask2|(1<<(node-1)));\n for(auto it:adj2[node]){\n if(it!=prev){\n dfs(it,node,adj2,mask2);\n }\n }\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\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 vector<int>res(n-1);\n for(int i=3;i<=(1<<n);i++){\n int mask=i;\n vector<int>adj2[n+1];\n int start=1;\n for(auto it:edges){\n int u=it[0];\n int v=it[1];\n if((mask&(1<<(u-1)))&&(mask&(1<<(v-1)))){\n start=u;\n adj2[u].push_back(v);\n adj2[v].push_back(u);\n }\n }\n int mask2=0;\n dfs(start,-1,adj2,mask2);\n if(mask2==mask){\n int ans = 0;\n int maxinode = 0;\n \n dfs(start, -1, 0, adj2, maxinode, ans);\n dfs(maxinode, -1, 0, adj2, maxinode, ans);\n res[ans-1]++;\n }\n }\n return res;\n }\n};\n```
1
0
['C++']
0
count-subtrees-with-max-distance-between-cities
C++ code with detailed explanation
c-code-with-detailed-explanation-by-anur-0031
While reading the question, the first intuition is that we are going to find out the distance between every pair of cities. Here, a subtree is essentially a con
anuragdub3y
NORMAL
2022-08-01T06:58:38.715663+00:00
2023-07-07T20:34:56.079647+00:00
134
false
While reading the question, the first intuition is that we are going to find out the distance between every pair of cities. Here, a subtree is essentially a connected graph (that may or may not contain all n cities but the cities that **are** included, are connected). We\'ll check the constraints, and we find that ```n<=15```. This tells us that we can go ahead and apply Floyd Warshall\'s Algorithm (since it works in O(n^3)).\n\n```\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> a(n,vector<int>(n,999));\n for(auto edge:edges){\n a[edge[0]-1][edge[1]-1]=1;\n a[edge[1]-1][edge[0]-1]=1;\n }\nfor(int k=0; k<n; k++){\n\tfor(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n a[i][j]=min(a[i][j],a[i][k]+a[k][j]);\n }\n }\n }\n```\nNow that we know all the distances between all cities, we need to generate all the subsets of connected cities and find their maximum distances. Again, n is small enough to carry out O(2^n) subset generation. Similar to what we do while generating subsets, we\'ll check if a bit is set and include corresponding city in our subset. If two cities are included, we\'ll find the distance between them. If the number of edges in this subset is satisfactory, we\'ll add the max distance in this subset to our ans array.\n\n```\nvector<int> ans(n-1,0);\n for (int s = 0; s < (1 << n); s++) {\n int k = __builtin_popcount(s); // The number of cities we\'ll have in our subset\n int numEdges = 0;\n int d = 0;\n for (int i = 0; i < n; i++){ \n if (s & (1 << i)) { \n for (int j = i + 1; j < n; j++) { \n if (s & (1 << j)) { \n numEdges += (a[i][j] == 1); \n d = max(d, a[i][j]);\n }\n }\n }\n }\n if (numEdges == k - 1 && d > 0) {\n ans[d - 1]++;\n }\n }\n \n return ans;\n\t}\n```
1
0
['C']
0
count-subtrees-with-max-distance-between-cities
C++| 4 easy Steps | brute-force
c-4-easy-steps-brute-force-by-kumarabhi9-q687
At first the glance, this problem looks complex and coming up with an optimal approach seems difficult but, we actually do not need to think that deep. Since co
kumarabhi98
NORMAL
2022-03-08T11:29:56.583804+00:00
2022-03-08T11:31:56.140978+00:00
248
false
At first the glance, this problem looks complex and coming up with an optimal approach seems difficult but, we actually do not need to think that deep. Since constraint is vey small, we can try the brute force. The solution is divide into 4 steps:\n1. Firstly build a graph using `edges`\n1. Generate all possible combination of nodes using **bitmask**\n1. Now check if all those nodes are connected or not using **DSU**, if not connected simply return. I have used **DSU**, you can simply use DFS or any other tool\n1. find the **diameter of subtree** from any node ( similar to [Diameter of Binary Tree](http://leetcode.com/problems/diameter-of-binary-tree/description/))\n\nupvote if it helps\n```\nclass Solution {\npublic:\n int mp[15] = {};\n int find(vector<int> &nums,int i){\n if(nums[i]==-1) return i;\n else return nums[i] = find(nums,nums[i]);\n }\n void union_(vector<int> &nums,int x,int y){\n int i = find(nums,x), j=find(nums,y);\n if(i!=j){\n if(i<j) nums[j] = i;\n else nums[i] = j;\n }\n }\n int findmaxdist(vector<vector<int>> &nums,vector<bool> &arr,int vis,int in, int &sum){ // to find diameter of subtree\n arr[in] = 1; int re = 0;\n priority_queue<int,vector<int>,greater<int>> q;\n for(int i = 0; i<nums[in].size();++i){\n int j = nums[in][i];\n if(bool(vis&(1<<j)) && arr[j]==0){\n int k = findmaxdist(nums,arr,vis,j,sum); re=max(re,k);\n q.push(k); if(q.size()>2) q.pop();\n }\n }\n int p = 0;\n while(!q.empty()){ p+=q.top(); q.pop(); }\n\t\t\n sum=max(sum,p);\n return re+1;\n }\n void count(vector<vector<int>> g,int vis,int n){\n vector<int> nums(n,-1); int l = 0;\n for(int i = 0; i<n;++i){\n if((vis&(1<<i))){\n l=i;\n for(int j = 0; j<g[i].size();++j){\n int k = g[i][j];\n if((vis&(1<<k))) union_(nums,i,k);\n }\n }\n }\n int re = 0;\n for(int i = 0; i<n;++i){\n if((vis&(1<<i))) if(nums[i]==-1) re++;\n }\n if(re!=1) return;\n vector<bool> arr(n,0);\n int k = 0;\n findmaxdist(g,arr,vis,l,k);\n mp[k]++;\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& arr) {\n vector<vector<int>> nums(n);\n for(int i = 0; i<arr.size();++i){\n nums[arr[i][0]-1].push_back(arr[i][1]-1);\n nums[arr[i][1]-1].push_back(arr[i][0]-1);\n }\n int last = (1<<n);\n for(int i = 1; i<last;++i) count(nums,i,n);\n vector<int> re;\n for(int i = 1; i<n;++i) re.push_back(mp[i]);\n return re;\n }\n};\n```
1
0
['Graph', 'C']
0
count-subtrees-with-max-distance-between-cities
C++ 0ms faster than 100% no need for bit mask, straightforward dfs
c-0ms-faster-than-100-no-need-for-bit-ma-3mvb
Iterates through all possible subtrees\n\nclass Solution {\npublic:\n struct Node {\n vector<int> children;\n };\n \n vector<int> countSubgraphsForEachDi
vvhack
NORMAL
2021-06-28T08:25:41.848004+00:00
2021-06-28T23:52:59.869787+00:00
408
false
Iterates through all possible subtrees\n```\nclass Solution {\npublic:\n struct Node {\n vector<int> children;\n };\n \n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<int> result(n - 1, 0); // Will store final result\n vector<Node> tree(n + 1); // Will contain the tree\n vector<bool> visited(n + 1, false); // Useful for dfs later\n \n // Build the tree\n for (auto& edge : edges) {\n tree[edge[0]].children.push_back(edge[1]);\n tree[edge[1]].children.push_back(edge[0]);\n }\n \n // Find diameters for all subtrees rooted at node 1 (arbitrary choice for root)\n computeDiameters(tree, 1, visited, result);\n return result;\n }\n \n struct SubTreeInfo {\n int depth;\n int diameter;\n SubTreeInfo(int depth, int diameter) : depth(depth), diameter(diameter) {}\n };\n \n vector<SubTreeInfo> computeDiameters(vector<Node>& tree, int nodeIdx, vector<bool>& visited,\n vector<int>& result) {\n auto& node = tree[nodeIdx];\n vector<SubTreeInfo> subTrees; // Will store information for subtrees rooted at node\n subTrees.push_back(SubTreeInfo(0, 0)); // First subtree just contains this node itself\n visited[nodeIdx] = true; // Mark this node as visited\n \n for (int childIdx : node.children) {\n if (visited[childIdx]) continue; // Ignore if this child is actually the parent\n int numSubTrees = subTrees.size(); // Number of subtrees built so far\n \n // Get subtrees for this child\n auto childSubTrees = computeDiameters(tree, childIdx, visited, result);\n for (auto& childSubTree : childSubTrees) {\n // Combine the child subtree with every subtree known so far\n for (int i = 0; i < numSubTrees; ++i) {\n auto& subTree = subTrees[i];\n SubTreeInfo newSubTree(-1, -1);\n \n // Compute the depth of this new subtree\n newSubTree.depth = max(subTree.depth, 1 + childSubTree.depth);\n // Compute the diameter of this new subtree (Note: child can have bigger diameter too)\n newSubTree.diameter = max(max(subTree.diameter, 1 + childSubTree.depth + \n subTree.depth), childSubTree.diameter);\n \n // Populate the results array\n result[newSubTree.diameter - 1]++;\n // Record this subtree for future use by parent of the current node\n subTrees.push_back(newSubTree);\n }\n }\n }\n return subTrees;\n }\n};\n```
1
0
[]
1
count-subtrees-with-max-distance-between-cities
C++ | Subsets| Bitmask
c-subsets-bitmask-by-tanishbothra22-i4w9
\nclass Solution {\npublic:\n int res=0;//for each subset max distance\n int sz=0;//to check whether every node of the subset in connected or not\n int dfs(i
tanishbothra22
NORMAL
2021-06-05T05:30:42.725705+00:00
2021-06-05T05:32:18.483125+00:00
216
false
```\nclass Solution {\npublic:\n int res=0;//for each subset max distance\n int sz=0;//to check whether every node of the subset in connected or not\n int dfs(int node,int mask,vector<vector<int>>&adj){\n \n int max_dia=0;//for the current node max diameter i.e max length including the current node\n sz++;\n for(auto x:adj[node]){\n if(mask&(1<<(x-1))){\n int dia= 1+dfs(x,mask^(1<<(x-1)),adj);\n res=max(res,dia+max_dia);\n max_dia=max(max_dia,dia);\n\n }\n }\n return max_dia;\n \n }\n \n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n \n vector<vector<int>>adj(n+1);\n for(int i=0;i<edges.size();i++){\n \n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n \n }\n \n vector<int>v(n-1,0);\n \n for(int i=0;i<(1<<n);i++){\n for(int j=0;j<=n-1;j++){\n if(i&(1<<j)){\n res=0;\n sz=0;\n dfs(j+1,i^(1<<j),adj);\n //sz== __builtin_popcount(i) is used to check number of set bits in the current subset\n if(res>0 && sz== __builtin_popcount(i)){\n v[res-1]++;\n }\n //break statement is used because we are just picking the first node present in the subset and then simply calculating the longest distance in the current subset \n//therefore doesn\'t make any sense by calculating longest path from every node as the result will be same for the same subset\n break;\n }\n }\n }\n \n return v;\n \n \n }\n};\n\n```
1
0
['C']
0
count-subtrees-with-max-distance-between-cities
JavaScript: All Subsets + DFS (diameter) solution
javascript-all-subsets-dfs-diameter-solu-a7sw
Reference: 1245. Tree Diameter\nProblem break-down:\n- Step1: build adjacent list\n- Step2: enumerate every possible subsets: bit-mask total = 2^n\n- Step3: ext
jialihan
NORMAL
2021-02-11T09:48:41.697009+00:00
2021-02-11T09:48:41.697078+00:00
121
false
Reference: [1245. Tree Diameter](https://leetcode.com/problems/tree-diameter/)\nProblem break-down:\n- Step1: build adjacent list\n- Step2: enumerate every possible subsets: bit-mask `total = 2^n`\n- Step3: extract each sub-tree number\n- Step4: **isValid & isConnected** sub-tree and Run DFS\n\t- true: only when `visited nodes size === sub-tree size`\n\t- Attention: use a different Set() to memo this info, different from the Set() used in **backtracking** ( will be empty at the end)\n- Step5: after run twice DFS, find the maxDiameter for current sub-tree, update to result array, count + 1;\n\n\n```js\nvar countSubgraphsForEachDiameter = function(n, edges) {\n function buildAdj(edges,n)\n {\n var adj = new Array(n).fill(0).map(el=>new Array(0));\n for(var e of edges)\n {\n adj[e[0]-1].push(e[1]-1);\n adj[e[1]-1].push(e[0]-1);\n }\n return adj;\n }\n function dfs(cur, dist, visited, nums)\n {\n nodes.add(cur);\n\n if(visited.has(cur))\n {\n return;\n }\n if(maxDist<dist )\n {\n maxDist = dist;\n farthest = cur;\n }\n visited.add(cur);\n for(var next of adj[cur])\n { \n if(nums.includes(next)) \n dfs(next, dist+1, visited, nums); \n }\n visited.delete(cur);\n }\n var res = new Array(n-1).fill(0);\n // step1: build adj\n var adj = buildAdj(edges,n);\n \n // step2: try 2^n possible subtrees\n for(var state = 1; state< (1<<n); state++)\n {\n // 2.1 extract the subtree\n var nums = [];\n for(var i= 0; i<n;i++)\n {\n if( ((state>>i) & 1) === 1)\n {\n nums.push(i);\n }\n \n }\n\n if(nums.length<2)\n {\n continue;\n }\n \n // 2.2 is connected and find the diameter\n var visited = new Set();\n var maxDist = -1;\n var farthest = -1;\n var nodes = new Set(); // traversed all nodes\n dfs(nums[0],0, visited, nums);\n if(nodes.size < nums.length)\n {\n // invalid tree: all visited size != nodes size\n continue;\n }\n maxDist = 0;\n visited.clear();\n dfs(farthest,0,visited, nums);\n \n // 2.3.find max dist, add to result\n if(maxDist>0)\n {\n res[maxDist-1]++;\n }\n }\n return res;\n};\n```\n
1
0
[]
0
count-subtrees-with-max-distance-between-cities
C++ bitmask brute force
c-bitmask-brute-force-by-sanzenin_aria-lmx5
```\nclass Solution {\npublic:\n vector countSubgraphsForEachDiameter(int n, vector>& edges) {\n g.resize(n);\n for(auto& e:edges){\n
sanzenin_aria
NORMAL
2021-01-23T18:14:04.661803+00:00
2021-01-23T18:14:04.661847+00:00
157
false
```\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n g.resize(n);\n for(auto& e:edges){\n g[e[0]-1].push_back(e[1]-1);\n g[e[1]-1].push_back(e[0]-1);\n }\n \n vector<int> res(n-1);\n for(int mask = 1; mask < (1<<n); mask++){\n int visited = 0, diameter = 0;\n depth(mask, findAnyIn(mask), visited, diameter);\n if(visited == mask && diameter>0) res[diameter-1]++;\n }\n return res;\n }\n \n // return -1 if invalid subtree\n int depth(int mask, int i, int& visited, int& diameter) const{\n add(i, visited);\n vector<int> vdepth = {0,0}; //add 0 so later don\'t need to check size\n for(auto j:g[i]){\n if(in(j, visited) || !in(j, mask)) continue;\n vdepth.push_back(depth(mask, j, visited, diameter));\n }\n sort(vdepth.begin(), vdepth.end(), greater());\n diameter = max(diameter, vdepth[0] + vdepth[1]);\n return 1+vdepth[0];\n }\n \n bool in(int i, int mask) const{\n return (1<<i) & mask;\n }\n \n void add(int i, int& mask) const{\n mask |= (1<<i);\n }\n \n int findAnyIn(int mask){\n int i = 0;\n while(!(mask & 1)){\n i++;\n mask >>=1;\n } \n return i;\n }\n \n vector<vector<int>> g;\n};
1
0
[]
0
count-subtrees-with-max-distance-between-cities
Java - subsets with bit masking - diameters with DFS
java-subsets-with-bit-masking-diameters-vuvkj
```\nclass Solution {\n \n private boolean[] beingVisited;\n private List> graph;\n private Set> subsets = new HashSet<>();\n \n public int[]
sukbah16
NORMAL
2020-12-19T07:46:20.715139+00:00
2020-12-20T06:31:01.026331+00:00
166
false
```\nclass Solution {\n \n private boolean[] beingVisited;\n private List<Set<Integer>> graph;\n private Set<Set<Integer>> subsets = new HashSet<>();\n \n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n this.beingVisited = new boolean[n];\n int[] counts = new int[n-1];\n counts[0] = edges.length;\n \n initializeGraph(n, edges);\n initializeSubsets(n);\n \n for(Set<Integer> subset : this.subsets) {\n //find diameter of graph formed by vertices in subset\n counts[diameter(subset)-1]++;\n }\n return counts;\n }\n\n private void initializeSubsets(int n) {\n for(int i = (1 << n); i < (1 << n + 1); i++) {\n String bitmask = Integer.toBinaryString(i).substring(1); \n \n Set<Integer> subset = new HashSet<>();\n for(int j=0; j<bitmask.length(); j++) {\n if(bitmask.charAt(j)==\'1\'){\n subset.add(j+1);\n }\n }\n\n if(subset.size() <= 2) continue;\n \n //check validity of subset - vertices must have n-1 edges among them\n int edgeCount = 0;\n for(Integer node : subset) {\n for(int adjacent : graph.get(node-1)) {\n if(subset.contains(adjacent)) {\n edgeCount++;\n }\n }\n }\n \n if((edgeCount/2) >= subset.size() - 1) {\n this.subsets.add(subset);\n } \n }\n }\n \n private int diameter(Set<Integer> subset) {\n //find farthest vertex from any vertex\n FarthestNode farthestNode = farthestNode(subset.iterator().next(), subset, 0);\n //get diameter of path from vertex found in previous step\n return farthestNode(farthestNode.node, subset, 0).distance;\n }\n \n private FarthestNode farthestNode(int node, Set<Integer> subset, int distance) {\n beingVisited[node-1] = true;\n FarthestNode farthestNode = new FarthestNode(node, distance);\n \n for(Integer adjacent : graph.get(node-1)) {\n \n if(!beingVisited[adjacent-1] && subset.contains(adjacent)) {\n \n FarthestNode otherFarthestNode = farthestNode(adjacent, subset, distance + 1);\n \n if(otherFarthestNode.distance > farthestNode.distance) {\n farthestNode = otherFarthestNode;\n }\n }\n }\n beingVisited[node-1] = false;\n return farthestNode;\n }\n \n private void initializeGraph(int n, int[][] edges) {\n this.graph = new ArrayList<>();\n for(int i=0; i<n; i++){\n graph.add(new HashSet<>());\n }\n for(int[] edge : edges) {\n graph.get(edge[0]-1).add(edge[1]);\n graph.get(edge[1]-1).add(edge[0]);\n }\n }\n \n private static class FarthestNode {\n int node;\n int distance;\n FarthestNode(int node, int distance) {\n this.node = node;\n this.distance = distance;\n }\n }\n}
1
1
[]
0
count-subtrees-with-max-distance-between-cities
[Java] Powerset solution + find max distance
java-powerset-solution-find-max-distance-cji3
\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n List<List<Integer>> graph = new ArrayList<>();\n for
roka
NORMAL
2020-10-12T20:09:07.661408+00:00
2020-10-12T20:09:07.661450+00:00
139
false
```\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n List<List<Integer>> graph = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n graph.add(new ArrayList<>());\n }\n \n for (int[] edge : edges) {\n graph.get(edge[0] - 1).add(edge[1] - 1);\n graph.get(edge[1] - 1).add(edge[0] - 1);\n }\n \n int[] answer = new int[n - 1];\n \n for (int bits = 1; bits < (1 << n); bits++) {\n Set<Integer> nodes = new HashSet<>();\n \n for (int j = 0; j < n; j++) {\n if (((1 << j) & bits) != 0) nodes.add(j);\n }\n \n if (isSubtree(graph, nodes)) {\n answer[maxDistance(graph, nodes) - 1]++;\n }\n }\n \n return answer;\n }\n \n private boolean isSubtree(List<List<Integer>> edges, Set<Integer> nodes) {\n if (nodes.size() < 2) {\n return false;\n }\n \n Queue<Integer> queue = new LinkedList<>();\n Set<Integer> visited = new HashSet<>();\n queue.add(nodes.iterator().next());\n visited.add(queue.peek());\n \n while (!queue.isEmpty()) {\n int cur = queue.poll();\n \n for (int edge : edges.get(cur)) {\n if (!visited.contains(edge) && nodes.contains(edge)) {\n visited.add(edge);\n queue.add(edge);\n }\n }\n }\n \n return visited.size() == nodes.size();\n }\n \n private int maxDistance(List<List<Integer>> edges, Set<Integer> nodes) {\n int deepest = findFarthestNode(edges, nodes, nodes.iterator().next(), -1).getKey();\n return findFarthestNode(edges, nodes, deepest, -1).getValue();\n }\n \n private Pair<Integer, Integer> findFarthestNode(List<List<Integer>> edges, Set<Integer> nodes, int cur, int from) {\n Pair<Integer, Integer> answer = new Pair(cur, 0);\n \n for (int edge : edges.get(cur)) {\n if (edge == from || !nodes.contains(edge)) {\n continue;\n }\n \n Pair<Integer, Integer> other = findFarthestNode(edges, nodes, edge, cur);\n if (other.getValue() + 1 > answer.getValue()) {\n answer = new Pair(other.getKey(), other.getValue() + 1);\n }\n }\n \n return answer;\n }\n}\n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
Simple C++ code by brutal force bit mask
simple-c-code-by-brutal-force-bit-mask-b-u93m
\nint countSubgraphsForEachDiameter_(int startIdx, int& nodes, vector<vector<int>>& conn, int& visited, int& maxDepth) {\n\tvisited |= (1 << startIdx);\n\tint f
luoyuf
NORMAL
2020-10-12T01:14:41.383991+00:00
2020-10-12T01:14:41.384033+00:00
88
false
```\nint countSubgraphsForEachDiameter_(int startIdx, int& nodes, vector<vector<int>>& conn, int& visited, int& maxDepth) {\n\tvisited |= (1 << startIdx);\n\tint first = 0, second = 0;\n\n\tfor (int i = 0; i < conn[startIdx].size(); ++i) {\n\t\tif ((nodes & (1 << conn[startIdx][i])) && !(visited & (1 << conn[startIdx][i]))) {\n\n\t\t\tint depth = countSubgraphsForEachDiameter_(conn[startIdx][i], nodes, conn, visited, maxDepth);\n\n\t\t\tif (depth >= first) {\n\t\t\t\tsecond = first;\n\t\t\t\tfirst = depth;\n\t\t\t} else {\n\t\t\t\tsecond = max(second, depth);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tmaxDepth = max(maxDepth, first + second);\n\treturn first + 1;\n}\n\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n\n\tvector<int> res(n - 1, 0);\n\tvector<vector<int>> conn(n);\n\n\tfor (int i = 0; i < edges.size(); ++i) {\n\t\tconn[edges[i][0] - 1].push_back(edges[i][1] - 1);\n\t\tconn[edges[i][1] - 1].push_back(edges[i][0] - 1);\n\t}\n\n\tfor (int i = 1; i < (1 << n); ++i) {\n\t\tint maxDepth = 0;\n\t\tint visited = 0;\n\n\t\tint startIdx = 0;\n\n\t\tfor (; (i & (1 << startIdx)) == 0; ++startIdx);\n\n\t\tcountSubgraphsForEachDiameter_(startIdx, i, conn, visited, maxDepth);\n\n\t\tif ((visited == i) && maxDepth > 0) ++res[maxDepth - 1];\n\n\t}\n\n\treturn res;\n}\n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
Java subset + check valid subtree + DFS
java-subset-check-valid-subtree-dfs-by-n-wgmg
Explanation from perspective of \u83DC\u9E1F like me:\n1. Get subset of all possibilities of 2 ^ n. Then the number from each subset could potentially becomes
nadabao
NORMAL
2020-10-12T00:42:17.223188+00:00
2020-10-12T00:44:06.276589+00:00
122
false
Explanation from perspective of \u83DC\u9E1F like me:\n1. Get subset of all possibilities of 2 ^ n. Then the number from each subset could potentially becomes a subtree. Say we choose subset [1, 2] from [1,2,3,4].\n\nActually I don\'t know if this is the standard approach for similar subtree questions? During contest I\'ve never thought in this way. I directly start searching the graph but of course not work. \n\nbtw, one advanced approach for getting subsets is to apply bitmask magic. And I don\'t know if traditional backtracking would result in TLE or not.\n\n2. However, NOT all subset can really form a subtree. The criterion for being valid subtree: \nThe number of nodes in subtree == number of edges in subtree + 1.\nAnd also subtree.size() != 1\nSince edges.length is quite short, just traverse the edges and easiy figure out number of edges.\n\n3. Once you have a valid subtree, then this question deteriorates into tree diameter question. Then can solve by two BFS or DFS as we see in "1245 Tree Diameter"\n\n\n```\nclass Solution {\n int maxPath = 0;\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n int[] res = new int[n - 1];\n \n // Preparation to contruct graph\n List<Integer>[] adjs = new List[n + 1];\n for (int i = 1; i <= n; i++) {\n adjs[i] = new ArrayList<>();\n }\n \n for (int[] edge : edges) {\n adjs[edge[0]].add(edge[1]);\n adjs[edge[1]].add(edge[0]);\n }\n \n // Get subset\n int total = 1 << n; // 2 ^ n subsets\n for (int i = 0; i < total; i++) {\n Set<Integer> subset = new HashSet<>();\n for (int j = 0; j < n; j++) {\n if ((i & (1 << j)) > 0) { // bitmask to find subsets\n subset.add(j + 1);\n }\n }\n \n // Check if subset is valid tree.\n // node # should be edge count + 1;\n int count = 0; // edge count\n for (int[] edge : edges) {\n if (subset.contains(edge[0]) &&\n subset.contains(edge[1])) {\n count++;\n }\n }\n if (subset.size() == 1 || subset.size() != count + 1) continue;\n \n int start = 0;\n for (int num : subset) {\n start = num;\n break;\n }\n \n maxPath = 0;\n\t\t\t// dfs to find max path for each subtree\n dfs(start, -1, subset, adjs);\n res[maxPath - 1]++;\n }\n\n return res;\n }\n \n private int dfs(int root, int parent, Set<Integer> subtree, List<Integer>[] adjs) {\n int firstMax = 0, secondMax = 0;\n for (int child : adjs[root]) {\n if (child == parent || !subtree.contains(child)) continue;\n int childLen = dfs(child, root, subtree, adjs) + 1;\n if (childLen > firstMax) {\n secondMax = firstMax;\n firstMax = childLen;\n } else if (childLen > secondMax) {\n secondMax = childLen;\n }\n }\n maxPath = Math.max(maxPath, firstMax + secondMax);\n return firstMax;\n }\n}\n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
C# Bitmask + DFS 2^N*N
c-bitmask-dfs-2nn-by-leoooooo-bbkp
\npublic class Solution {\n public int[] CountSubgraphsForEachDiameter(int n, int[][] edges) {\n List<int>[] graph = new List<int>[n];\n for(in
leoooooo
NORMAL
2020-10-11T19:16:54.220524+00:00
2020-10-11T19:55:34.350018+00:00
88
false
```\npublic class Solution {\n public int[] CountSubgraphsForEachDiameter(int n, int[][] edges) {\n List<int>[] graph = new List<int>[n];\n for(int i = 0; i < n; i++)\n graph[i] = new List<int>();\n foreach(int[] e in edges)\n {\n graph[e[0]-1].Add(e[1]-1);\n graph[e[1]-1].Add(e[0]-1);\n }\n \n int[] res = new int[n-1];\n for(int mask = 1; mask < 1 << n; mask++)\n {\n int x = 0, visited = 0, max = 0;\n while((mask & 1 << x) == 0)\n x++;\n MaxDiameter(x, -1, graph, mask, ref visited, ref max); \n if(mask == visited && max > 0)\n res[max-1]++;\n }\n return res;\n }\n \n private int MaxDiameter(int x, int p, List<int>[] graph, int mask, ref int visited, ref int max)\n {\n int max1 = 0, max2 = 0;\n visited |= 1 << x;\n foreach(int next in graph[x])\n {\n if(next == p || (mask & 1 << next) == 0) continue;\n int d = MaxDiameter(next, x, graph, mask, ref visited, ref max) + 1;\n if(d > max1)\n {\n max2 = max1;\n max1 = d;\n }\n else if (d > max2)\n max2 = d;\n }\n \n max = Math.Max(max, max1 + max2);\n return max1;\n }\n}\n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
[C++] O(2^N*N) BitMask + DFS
c-o2nn-bitmask-dfs-by-louisfghbvc-fueb
\t\n\tclass Solution {\n\tpublic:\n\t\tint mx, mxp, cnt; // diameter, farthest point, graph node count\n\t\tvector g[17];\n\t\tvoid dfs(int u, int d, int p){ //
louisfghbvc
NORMAL
2020-10-11T10:44:58.427547+00:00
2020-10-11T10:56:25.904779+00:00
137
false
\t\n\tclass Solution {\n\tpublic:\n\t\tint mx, mxp, cnt; // diameter, farthest point, graph node count\n\t\tvector<int> g[17];\n\t\tvoid dfs(int u, int d, int p){ // current node, depth, parent node\n\t\t\tcnt++;\n\t\t\tif(d > mx){\n\t\t\t\tmx = d;\n\t\t\t\tmxp = u;\n\t\t\t}\n\t\t\tfor(int v: g[u]){\n\t\t\t\tif(v != p){\n\t\t\t\t\tdfs(v, d+1, u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n\t\t\tvector<int> res(n-1);\n\t\t\tfor(int i = 1; i < (1<<n); ++i){ // enum all subset\n\t\t\t\tif(__builtin_popcount(i) == 1) continue;\n\t\t\t\tfor(int j = 0; j <= n; ++j) g[j].clear();\n\n\t\t\t\tint pt = -1; // random pick a point in graph as a start point\n\t\t\t\tfor(auto &e: edges){\n\t\t\t\t\tint u = e[0]-1, v = e[1]-1;\n\t\t\t\t\tif( ((1<<u)&i) && ((1<<v)&i) ){ // make sure the edge point must be in the mask\n\t\t\t\t\t\tg[u].emplace_back(v);\n\t\t\t\t\t\tg[v].emplace_back(u);\n\t\t\t\t\t\tif(pt == -1) pt = u;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(pt == -1) continue;\n\t\t\t\t\n\t\t\t\t/**\n\t\t\t\t\tTwo dfs, one is from a start point find the farthest point.\n\t\t\t\t\tSecond, from that farthest point. Again find the other farthest point.\n\t\t\t\t\tFinally, distance is diameter.\n\t\t\t\t**/\n\t\t\t\t\n\t\t\t\tmx = 0, mxp = -1, cnt = 0;\n\t\t\t\tdfs(pt, 0, -1);\n\t\t\t\tmx = 0, cnt = 0;\n\t\t\t\tdfs(mxp, 0, -1);\n\t\t\t\tif(cnt == __builtin_popcount(i) && mx > 0){\n\t\t\t\t\tres[mx-1]++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t};
1
0
['Depth-First Search', 'C']
0
count-subtrees-with-max-distance-between-cities
[Python DFS] for each subtree, find its diameter
python-dfs-for-each-subtree-find-its-dia-e31t
DFS to find all subtrees (expand_tree).\nFor each subtree, DFS to find its diameter (get_diameter).\nCode self-explains, with inline comments:\n\nfrom functools
kaiwensun
NORMAL
2020-10-11T05:28:06.618937+00:00
2020-10-11T05:53:24.530720+00:00
195
false
DFS to find all subtrees (`expand_tree`).\nFor each subtree, DFS to find its diameter (`get_diameter`).\nCode self-explains, with inline comments:\n```\nfrom functools import lru_cache\nfrom collections import defaultdict\n\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n \n def each_one_bit(binary):\n while binary:\n next_binary = binary & binary - 1\n yield binary - next_binary # yield the right-most bit 1 of `binary`\n binary = next_binary\n\n def get_diameter(node, subtree, frm):\n depth = max_res = 0\n for neighbor in each_one_bit(graph[node]):\n if neighbor == frm:\n continue # do not go back\n if neighbor & subtree == 0:\n continue # neighbor not in subtree\n this_depth, this_max_res = get_diameter(neighbor, subtree, node)\n max_res = max(max_res, this_max_res, depth + this_depth)\n depth = max(depth, this_depth)\n return depth + 1, max_res # (max depth, max diameter)\n\n @lru_cache(1 << n) # do not search a same subtree again\n def expand_tree(subtree):\n _, max_res = get_diameter(subtree - ((subtree - 1) & subtree), subtree, 0) # find the diameter of the subtree, by DFS from the smallest node\n res[max_res] += 1\n for shift in range(n):\n candidate = 1 << shift # candidate to expand from the subtree\n if candidate & subtree != 0:\n continue # already in subtree\n candidate_neighbors = graph[candidate]\n if candidate_neighbors & subtree == 0:\n continue # not connected\n expand_tree(subtree | candidate)\n \n # make graph\n graph = defaultdict(int)\n for u, v in edges:\n graph[1 << (u - 1)] |= 1 << (v - 1)\n graph[1 << (v - 1)] |= 1 << (u - 1)\n res = [0] * n\n # expand subtrees from each single node\n for shift in range(n):\n expand_tree(1 << shift)\n return res[1:]\n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
[Java] Build subtrees recursively O(n^2 * number of subtrees)
java-build-subtrees-recursively-on2-numb-t11w
I thought I would share a different idea.\nI generate the list of all subtrees recursively, by "removing a leaf" every time. To find the order of leaves, I used
s_tsat
NORMAL
2020-10-11T05:20:04.111469+00:00
2020-10-11T05:31:13.205600+00:00
358
false
I thought I would share a different idea.\nI generate the list of all subtrees recursively, by "removing a leaf" every time. To find the order of leaves, I used dfs preorder.\nTo find the distances between all pairs of vertices I used BFS.\nOther than that, the code should be pretty straitforward (but pretty long, I know).\n\nThe time complexity should be O(n^2 * number of subtrees) : building the list of subtrees takes time O(n * number of subtrees), and checking the distances for each subtree takes O(n^2 * number of subtrees). Unfortunately, the number of trees can be as large as ~2^(n - 1) for the star, so the worst case complexity is the same as checking all subsets.\n\n```\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n ArrayList<Integer>[] graph = (ArrayList<Integer>[]) new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n for (int[] edge : edges){\n graph[edge[0] - 1].add(edge[1] - 1);\n graph[edge[1] - 1].add(edge[0] - 1);\n }\n List<Integer> postOrder = new ArrayList<>();\n getPostorder(graph, 0, new boolean[n], postOrder);\n \n int[][] distances = new int[n][n];\n for (int i = 0; i < n; i++)\n calculateDistances(graph, i, distances);\n\n List<List<Integer>> subtrees = buildAllSubtrees(graph, new boolean[n], postOrder, 0);\n int[] ans = new int[n - 1];\n for (List<Integer> subTree : subtrees){\n if (subTree.size() < 2) continue;\n\t\t\t\n\t\t\t// find the maximum distance between two vertices from this subtree\n int max = -1;\n for (int i = 0; i < subTree.size(); i++)\n for (int j = i + 1; j < subTree.size(); j++)\n max = Math.max(max, distances[subTree.get(i)][subTree.get(j)]);\n ans[max - 1]++;\n }\n\t\t\n return ans;\n }\n \n // get the postorder of vertices using DFS\n \n private void getPostorder(ArrayList<Integer>[] graph, int start, boolean[] visited, List<Integer> postOrder){\n visited[start] = true;\n for (int i : graph[start]){\n if (visited[i]) continue;\n getPostorder(graph, i, visited, postOrder);\n }\n postOrder.add(start);\n }\n \n // find distances between all pairs using BFS\n \n private void calculateDistances(ArrayList<Integer>[] graph, int start, int[][] distances){\n Queue<Integer> queue = new LinkedList<>();\n queue.add(start);\n int dist = 0;\n boolean[] visited = new boolean[distances.length];\n while (!queue.isEmpty()){\n int size = queue.size();\n for (int i = 0; i < size; i++){\n int vertex = queue.poll();\n visited[vertex] = true;\n distances[start][vertex] = dist;\n for (int neigh : graph[vertex]){\n if (!visited[neigh]) queue.add(neigh);\n }\n }\n dist++;\n }\n }\n \n \n // build the set of all subtrees by visiting vertices in the postorder\n // in this way the current vertex will always be the leaf in the subtree up to current\n \n private List<List<Integer>> buildAllSubtrees(ArrayList<Integer>[] graph, boolean[] visited, List<Integer> order, int current){\n if (current == order.size())\n return new ArrayList<>();\n \n int leaf = order.get(current);\n \n // find the unique neighbor of the leaf\n int neighbor = -1;\n for (int neigh : graph[leaf]){\n if (!visited[neigh]){\n neighbor = neigh;\n break;\n }\n }\n \n visited[leaf] = true;\n \n // find the subtrees if we remove the leaf\n List<List<Integer>> list = buildAllSubtrees(graph, visited, order, current + 1);\n \n // for each subset, if it contains the unique neighbor, add a copy of it with the leaf\n List<List<Integer>> newAns = new ArrayList<>();\n for (List<Integer> subTree : list){\n newAns.add(subTree);\n if (subTree.contains(neighbor)){\n List<Integer> newList = new ArrayList(subTree);\n newList.add(leaf);\n newAns.add(newList);\n }\n }\n \n // add the subtree that only contains leaf\n List<Integer> single = new ArrayList<>();\n single.add(leaf);\n newAns.add(single);\n \n return newAns;\n }
1
0
['Depth-First Search', 'Breadth-First Search', 'Recursion', 'Java']
0
count-subtrees-with-max-distance-between-cities
C++ O(n * 2^n) solution - bitmask + DFS
c-on-2n-solution-bitmask-dfs-by-ydchentw-p6mu
Iterate through all subsets: O(2^n) \nDFS: O(n)\nTime complexity: O(n * 2^n)\n```\nclass Solution {\npublic:\n using Tp = tuple;\n vector> adj;\n vecto
ydchentw
NORMAL
2020-10-11T05:07:07.057207+00:00
2020-10-11T05:09:17.347037+00:00
71
false
Iterate through all subsets: `O(2^n)` \nDFS: `O(n)`\nTime complexity: `O(n * 2^n)`\n```\nclass Solution {\npublic:\n using Tp = tuple<int, int, int>;\n vector<vector<int>> adj;\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n adj.resize(n);\n for (auto &e: edges) {\n adj[e[0]-1].push_back(e[1]-1);\n adj[e[1]-1].push_back(e[0]-1);\n }\n vector<int> ans(n-1, 0);\n\t\t// iterate through all subsets\n for (int mask = 1; mask < (1<< n); ++mask) {\n int x = mask;\n int root = 0;\n while (x) {\n if (x & 1) {\n x >>= 1;\n break;\n }\n ++root;\n x >>= 1;\n }\n if (x == 0) continue; // only one node\n int subset, max_path, depth;\n tie(subset, max_path, depth) = subtree_len(mask, root, root);\n if (subset == mask) { // check all nodes are reachable from root\n ans[max_path-1]++;\n }\n }\n return ans;\n }\n \n Tp subtree_len(int mask, int x, int p) {\n int max_path = 0, depth = 0;\n int max_child_depth = 0, second_child_depth = 0;\n int subset = (1 << x);\n for (int to: adj[x]) {\n if (to != p && (mask & (1<<to))) {\n int subtree_subset, subtree_max_path, subtree_depth;\n tie(subtree_subset, subtree_max_path, subtree_depth) = subtree_len(mask, to, x);\n subset |= subtree_subset;\n second_child_depth = max(second_child_depth, subtree_depth + 1);\n if (max_child_depth < second_child_depth) swap(max_child_depth, second_child_depth);\n max_path = max(subtree_max_path, max_path);\n depth = max(depth, subtree_depth + 1);\n }\n }\n max_path = max(max_path, depth);\n max_path = max(max_path, max_child_depth + second_child_depth);\n return {subset, max_path, depth};\n }\n};
1
0
[]
0
count-subtrees-with-max-distance-between-cities
[Python3] brute force
python3-brute-force-by-ye15-dlb8
Enumerate all combinations of edges. In each case, work out the subtrees and their max distance. Collect such info for the statistics. \n\nThis is a pretty cumb
ye15
NORMAL
2020-10-11T04:19:40.236866+00:00
2020-10-11T04:19:40.236911+00:00
247
false
Enumerate all combinations of `edges`. In each case, work out the subtrees and their max distance. Collect such info for the statistics. \n\nThis is a pretty cumbersome algo & implementation. Hopefully, there are better solutions out there. \n\n```\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n \n def fn(edges): \n """ """\n graph = {} # graph as adjacency list \n for u, v in edges:\n graph.setdefault(u-1, []).append(v-1) # 0-indexed \n graph.setdefault(v-1, []).append(u-1)\n group = [None]*n\n dist = [0]*n\n \n def dfs(x, d=0): \n """ """\n seen.add(x) # mark visited \n for xx in graph.get(x, []): \n dist[x] = max(dist[x], d)\n if group[xx] is None: group[xx] = group[x]\n if xx not in seen: dfs(xx, d+1)\n \n for i in range(n): \n seen = set()\n if group[i] is None: group[i] = i\n dfs(i)\n return group, dist \n \n ans = {} # answer \n for r in range(1, len(edges)+1):\n for x in combinations(edges, r): \n temp = {}\n d = {}\n seen, dist = fn(x)\n for i in range(n): \n temp.setdefault(seen[i], []).append(i)\n if seen[i] not in d: d[seen[i]] = dist[i]\n else: d[seen[i]] = max(d[seen[i]], dist[i])\n for k, v in temp.items(): \n if len(v) > 1: \n ans.setdefault(d[k], set()).add(tuple(sorted(v)))\n return [len(ans.get(x, set())) for x in range(1, n)]\n```
1
0
['Python3']
0
count-subtrees-with-max-distance-between-cities
Python backtracking with edges than nodes O(n*2^n)
python-backtracking-with-edges-than-node-djle
The key thing is, instead of determining which nodes to construct the subtree, use edges.\n\n1. Backtrack to find all subtree candidates\n\t1.1 for each candida
foobar_withgoogle
NORMAL
2020-10-11T04:04:14.786520+00:00
2020-10-11T04:08:48.453228+00:00
331
false
The key thing is, instead of determining which nodes to construct the subtree, use edges.\n\n1. Backtrack to find all subtree candidates\n\t1.1 for each candidate determine if it is a tree\n\t1.2 calculate the diameter of such tree\n\nTime complexcity is 14 * 2 ^ 14\uFF1B\n```\nclass Solution:\n \n def isTree(self, edges):\n \n graph = collections.defaultdict(set)\n matching = {}\n curIdx = 0\n for edge in edges:\n l, r = edge[0], edge[1]\n if l not in matching:\n matching[l] = curIdx\n curIdx += 1\n if r not in matching:\n matching[r] = curIdx\n curIdx += 1\n graph[matching[l]].add(matching[r])\n graph[matching[r]].add(matching[l])\n \n seen = [0] * curIdx\n\n def dfs(i):\n if seen[i]: return 0\n seen[i] = 1\n for j in graph[i]: dfs(j)\n return 1\n\n return sum(dfs(i) for i in range(curIdx)) - 1 == 0\n \n \n def getDofTree(self, edges, graph):\n graph = collections.defaultdict(set)\n matching = {}\n curIdx = 0\n for edge in edges:\n l, r = edge[0], edge[1]\n if l not in matching:\n matching[l] = curIdx\n curIdx += 1\n if r not in matching:\n matching[r] = curIdx\n curIdx += 1\n graph[matching[l]].add(matching[r])\n graph[matching[r]].add(matching[l])\n \n n = curIdx\n #print(graph)\n res = 0\n \n def getL(node, graph, parent):\n nonlocal res\n nonlocal n\n if not graph[node]:\n return 1\n hq = []\n for child in graph[node]:\n #print(child)\n if child == parent:\n continue\n heapq.heappush(hq, getL(child, graph, node))\n if len(hq) > 2:\n heapq.heappop(hq)\n res = max(res, sum(hq))\n if hq:\n return hq[-1] + 1\n else:\n return 1\n \n getL(0, graph, -1)\n return res\n\n \n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n \n res = [0 for _ in range(n)]\n maxGraph = collections.defaultdict(set)\n possiblePath = set()\n \n for edge in edges:\n maxGraph[edge[0]].add(edge[1])\n maxGraph[edge[1]].add(edge[0])\n #possiblePath.add((min(edge[0], edge[1]), max(edge[0], edge[1])))\n \n def bt(cur, curEdges, edges):\n if cur == n - 1: \n if len(curEdges) >= 1:\n if self.isTree(curEdges):\n res[self.getDofTree(curEdges, maxGraph)] += 1 \n return\n bt(cur + 1, curEdges + [edges[cur]], edges)\n bt(cur + 1, curEdges, edges)\n \n bt(0, [], edges)\n return res[1:]\n \n```
1
0
[]
0
count-subtrees-with-max-distance-between-cities
Python Hard
python-hard-by-lucasschnee-coby
null
lucasschnee
NORMAL
2025-02-06T03:39:29.275805+00:00
2025-02-06T03:39:29.275805+00:00
8
false
```python3 [] class UnionFind: def __init__(self, N): self.count = N self.parent = [i for i in range(N)] self.rank = [1] * N def find(self, p): if p != self.parent[p]: self.parent[p] = self.find(self.parent[p]) return self.parent[p] def union(self, p, q): prt, qrt = self.find(p), self.find(q) if prt == qrt: return False if self.rank[prt] >= self.rank[qrt]: self.parent[qrt] = prt self.rank[prt] += self.rank[qrt] else: self.parent[prt] = qrt self.rank[qrt] += self.rank[prt] self.count -= 1 return True class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: ''' 2 ** n works ''' N = n for i in range(len(edges)): edges[i][0] -= 1 edges[i][1] -= 1 # print(edges) A = [0] * N def bfs_farthest_node(start, graph): visited = [False] * n dist = [0] * n queue = deque([start]) visited[start] = True farthest_node = start while queue: node = queue.popleft() for neighbor in graph[node]: if not visited[neighbor]: visited[neighbor] = True dist[neighbor] = dist[node] + 1 queue.append(neighbor) if dist[neighbor] > dist[farthest_node]: farthest_node = neighbor return farthest_node, dist[farthest_node] def find_tree_diameter(e): seen = set() graph = defaultdict(list) for u, v in e: graph[u].append(v) graph[v].append(u) seen.add(u) # Start from any node (Node 0 in this case) for i in range(n): if i in seen: farthest_node, _ = bfs_farthest_node(i, graph) # Find the farthest node from the previously found farthest node farthest_node, diameter = bfs_farthest_node(farthest_node, graph) # print(graph, diameter) return diameter self.seen = set() def get_max_dist(mask): nodes = set() for i in range(n): if (1 << i) & mask: nodes.add(i) if len(nodes) == 1: return e = [] UF = UnionFind(N) m = 0 base = 0 for u, v in edges: if u in nodes and v in nodes: e.append((u, v)) m |= (1 << u) m |= (1 << v) base = u UF.union(u, v) if UF.rank[UF.find(base)] != len(nodes): return if m in self.seen: return self.seen.add(m) if not e: return A[find_tree_diameter(e)] += 1 for i in range(1, 1<<n): get_max_dist(i) return A[1:] # print(A) # for x in A[1:]: # total = 0 # for i in range(n): # if (1 << i) & x: # total += 1 # ans.append(total) # return ans ```
0
0
['Python3']
0
count-subtrees-with-max-distance-between-cities
Count Subtrees With Max Distance Between Cities solution in java
count-subtrees-with-max-distance-between-dt5n
Code
reachparthm
NORMAL
2025-01-20T17:19:59.626632+00:00
2025-01-20T17:19:59.626632+00:00
14
false
# Code ```java [] import java.util.*; class Solution { private int solve(int subtree, int[][] dist, int n) { int cntN = 0, cntE = 0, mxd = 0; for (int i = 0; i < n; i++) { if (((subtree >> i) & 1) == 0) continue; cntN++; for (int j = i + 1; j < n; j++) { if (((subtree >> j) & 1) == 0) continue; if (dist[i][j] == 1) { cntE++; } mxd = Math.max(mxd, dist[i][j]); } } if (cntN == cntE + 1) { return mxd; } return -1; } public int[] countSubgraphsForEachDiameter(int n, int[][] edges) { int[] result = new int[n - 1]; int[][] dist = new int[15][15]; // Initialize distance array for (int[] row : dist) { Arrays.fill(row, Integer.MAX_VALUE); } // Populate direct distances based on edges for (int[] edge : edges) { dist[edge[0] - 1][edge[1] - 1] = 1; dist[edge[1] - 1][edge[0] - 1] = 1; } // Floyd-Warshall to compute shortest paths for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] != Integer.MAX_VALUE && dist[j][k] != Integer.MAX_VALUE) { dist[i][j] = dist[j][i] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } } // Iterate over all subsets of nodes for (int i = 0; i < (1 << n); i++) { int ans = solve(i, dist, n); if (ans > 0) { result[ans - 1]++; } } return result; } public static void main(String[] args) { Solution solution = new Solution(); int n = 4; int[][] edges = {{1, 2}, {2, 3}, {2, 4}}; int[] result = solution.countSubgraphsForEachDiameter(n, edges); System.out.println(Arrays.toString(result)); } } ```
0
0
['Java']
0
count-subtrees-with-max-distance-between-cities
Bitmask with DSU
bitmask-with-dsu-by-viditgupta7001-f8ot
IntuitionAs the constraints are quite low, you can check for every possible subtree in the tree. Keep a 'mask' which will tell you all the nodes there are going
viditgupta7001
NORMAL
2025-01-17T13:32:03.466486+00:00
2025-01-17T13:32:03.466486+00:00
7
false
# Intuition As the constraints are quite low, you can check for every possible subtree in the tree. Keep a 'mask' which will tell you all the nodes there are going to be in your tree. After this form the new subtree from this mask. Form a new adjacency list for this new subtree and keep connecting the nodes using DSU. Now if after going through the mask your subtree is not a single component, then it is not a valid subtree candidate. If it is a single component, just find the diameter of the tree. To find the diameter: Pick any node (a) from this subtree. Find the farthest node (b) from this node. Once you find b, then from b find it's farthest node (c). The distance between b and c is the diameter of the tree. Hope it helps. Please upvote if you liked it. # 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 DSU{ private: vector<int>size; vector<int>parent; public: DSU(int n){ size.resize(n+1,1); parent.resize(n+1); iota(parent.begin(),parent.end(),0); } int findPar(int node){ if(node==parent[node])return node; return parent[node] = findPar(parent[node]); } void unite(int x,int y){ x = findPar(x); y = findPar(y); if(x==y)return; if(size[x] < size[y]){ size[y] += size[x]; parent[x] = y; } else{ size[x] += size[y]; parent[y] = x; } } }; class Solution { public: vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) { vector<int>ans(n); int fmask = (1 << n); vector<vector<int>>adj(n+1); for(auto &i:edges){ int a = i[0],b = i[1]; adj[a].push_back(b); adj[b].push_back(a); } auto dfs = [&](int node,int par,int d,int &md,int &index,auto &&adjj,auto &&self)->void{ if(d>md){ md = d; index = node; } for(auto &i:adjj[node]){ if(i!=par){ self(i,node,d+1,md,index,adjj,self); } } }; auto bfs = [&](int source,vector<vector<int>>&adjj)->void{ int md = 0,index = source; dfs(source,-1,0,md,index,adjj,dfs); md = 0; dfs(index,-1,0,md,index,adjj,dfs); if(md<=n-1)ans[md]++; }; auto calc = [&](int mask){ DSU ds(n); int source = -1; for(int i=0;i<=n;i++){ if((1<<i)&mask){ source = i+1; break; } } queue<int>q; unordered_set<int>m; m.insert(source); q.push(source); vector<vector<int>>adj1(n+1); while(!q.empty()){ int node = q.front(); q.pop(); for(auto i:adj[node]){ if(m.find(i)==m.end() && (1<<(i-1))&mask){ m.insert(i); ds.unite(node,i); adj1[node].push_back(i); adj1[i].push_back(node); q.push(i); } } } unordered_set<int>s; for(int i=0;i<n;i++){ if((1<<i)&mask){ s.insert(ds.findPar(i+1)); } } if(s.size()>1)return; bfs(source,adj1); }; for(int mask=1;mask<fmask;mask++){ calc(mask); } ans.erase(ans.begin()); return ans; } }; ```
0
0
['Bit Manipulation', 'Union Find', 'Bitmask', 'C++']
0
count-subtrees-with-max-distance-between-cities
1617. Count Subtrees With Max Distance Between Cities
1617-count-subtrees-with-max-distance-be-xkk0
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-14T12:50:35.707604+00:00
2025-01-14T12:50:35.707604+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 ```java [] class Solution { private int[][] distMatrix; public int[] countSubgraphsForEachDiameter(int n, int[][] roads) { distMatrix = new int[n][n]; List<Integer>[] graph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } for (int[] road : roads) { graph[road[0] - 1].add(road[1] - 1); graph[road[1] - 1].add(road[0] - 1); } for (int i = 0; i < n; i++) { calculateDistance(graph, i, -1, i, 0); } int[] diameterFrequency = new int[n - 1]; for (int mask = 1; mask < (1 << n); mask++) { int maxDist = 0; int singleEdgeCount = 0; int includedCities = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { includedCities++; for (int j = i + 1; j < n; j++) { if ((mask & (1 << j)) != 0) { maxDist = Math.max(maxDist, distMatrix[i][j]); if (distMatrix[i][j] == 1) { singleEdgeCount++; } } } } } if (singleEdgeCount == includedCities - 1 && maxDist > 0) { diameterFrequency[maxDist - 1]++; } } return diameterFrequency; } private void calculateDistance(List<Integer>[] graph, int origin, int prevCity, int currentCity, int distance) { if (prevCity == currentCity) { return; } distMatrix[origin][currentCity] = distance; distMatrix[currentCity][origin] = distance; for (int neighbor : graph[currentCity]) { if (neighbor != prevCity) { calculateDistance(graph, origin, currentCity, neighbor, distance + 1); } } } } ```
0
0
['Java']
0
count-subtrees-with-max-distance-between-cities
C# bitmask + Floyd–Warshall
c-bitmask-floyd-warshall-by-zloytvoy-j0ic
Intuition\nEnumerate all subsets of vertexes.\nFor each subset check if this forms a tree when adding edges.\nRun Floyd-Warshall and capture maximum distance. \
zloytvoy
NORMAL
2024-12-07T16:11:57.227392+00:00
2024-12-07T16:11:57.227412+00:00
2
false
# Intuition\nEnumerate all subsets of vertexes.\nFor each subset check if this forms a tree when adding edges.\nRun Floyd-Warshall and capture maximum distance. \nAdd 1 to the corresponding array index\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```csharp []\npublic class Solution {\n public int[] CountSubgraphsForEachDiameter(int n, int[][] edges) \n {\n var result = new int[n - 1];\n for(int mask = 1; mask <= (1 << n); ++mask)\n {\n var vertexes = new HashSet<int>();\n var matrix = new long[n, n];\n var edgesCount = 0;\n\n for(int i = 0; i < n; ++i)\n {\n if((mask & (1 << i)) > 0)\n {\n vertexes.Add(i);\n }\n }\n for(int i = 0; i < n; ++i)\n {\n for(int j = 0; j < n; ++j)\n {\n if(i != j)\n {\n matrix[i, j] = int.MaxValue;\n }\n }\n }\n\n foreach(var edge in edges)\n {\n var start = edge[0] - 1;\n var end = edge[1] - 1;\n if( vertexes.Contains(start) && \n vertexes.Contains(end) )\n {\n ++edgesCount;\n matrix[start, end] = 1;\n matrix[end, start] = 1;\n }\n }\n\n if(vertexes.Count - 1 == edgesCount && edgesCount > 0)\n {\n for(int k = 0; k < n; ++k)\n {\n for(int i = 0; i < n; ++i)\n {\n for(int j = 0; j < n; ++j)\n {\n matrix[i, j] = Math.Min(matrix[i, j], matrix[i, k] + \n matrix[k, j]);\n }\n }\n }\n\n var maxDistance = 0;\n for(int i = 0; i < n; ++i)\n {\n for(int j = 0; j < n; ++j)\n {\n if(matrix[i, j] != int.MaxValue)\n {\n maxDistance = (int)Math.Max(maxDistance, matrix[i, j]);\n }\n }\n }\n \n if(maxDistance > 0 && maxDistance <= n - 1)\n {\n result[maxDistance - 1] += 1; \n }\n }\n }\n\n return result;\n }\n}\n```
0
0
['C#']
0
count-subtrees-with-max-distance-between-cities
Step-by-step breakdown
step-by-step-breakdown-by-su-brat-zd8l
Approach\nAccepted brute force using:\n- Backtracking to find all subset graphs\n- BFS to check if the subset graph is connected and find the farthest leaf node
su-brat
NORMAL
2024-11-29T13:43:02.775763+00:00
2024-11-29T13:45:22.770382+00:00
7
false
# Approach\nAccepted brute force using:\n- Backtracking to find all subset graphs\n- BFS to check if the subset graph is connected and find the farthest leaf node\n- If it is connected then it is subtree as per the rule\n- DFS for finding the largest distance between any two nodes (in other words, farthest distance from the found leaf node)\n- Ultimately, increase the subtree count (initiated with zero) for the distance\n\n# Complexity\n- Time complexity:\n`O(2^n . n)`\n\n- Space complexity:\n`O(n)`\n\n# Code\n```python3 []\nclass Solution:\n def maximumSubtreeDistance(self, adj_list, node, parent, subtree):\n dist = 0\n for nbr in adj_list[node]:\n if parent != nbr and nbr in subtree:\n dist = max(dist, self.maximumSubtreeDistance(adj_list, nbr, node, subtree))\n if node == parent:\n return dist\n return dist + 1\n \n def checkValidSubtreeAndFarthestNode(self, subtree, adj_list, first_node):\n if len(subtree) == 0:\n return False\n visited = {node: False for node in subtree}\n dist = 0\n q = deque([(dist, first_node)])\n visited[first_node] = True\n farthest_node = first_node\n max_dist = 0\n while len(q) > 0:\n dist, node = q.popleft()\n if max_dist < dist:\n farthest_node = node\n max_dist = dist\n for nbr in adj_list[node]:\n if nbr in subtree and visited[nbr] is False:\n q.append((dist + 1, nbr))\n visited[nbr] = True\n return all(visited.values()), farthest_node\n \n def countSubtrees(self, adj_list, subtree, node, subtree_count):\n if node == len(adj_list):\n if len(subtree) == 0:\n return\n start_node = list(subtree)[0]\n valid_subtree, farthest_node = self.checkValidSubtreeAndFarthestNode(subtree, adj_list, start_node)\n if valid_subtree:\n dist = self.maximumSubtreeDistance(adj_list, farthest_node, farthest_node, subtree)\n subtree_count[dist] = subtree_count.get(dist, 0) + 1\n return\n self.countSubtrees(adj_list, subtree, node + 1, subtree_count)\n self.countSubtrees(adj_list, set(list(subtree) + [node]), node + 1, subtree_count)\n \n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n subtree_count = {}\n subtree = set()\n adj_list = {node: [] for node in range(n)}\n for (u, v) in edges:\n node, nbr = u-1, v-1\n adj_list[node].append(nbr)\n adj_list[nbr].append(node)\n start_node = 0\n self.countSubtrees(adj_list, subtree, start_node, subtree_count)\n ans = []\n no_subtree_cnt = 0\n for d in range(1, n):\n ans.append(subtree_count.get(d, no_subtree_cnt))\n return ans\n```
0
0
['Graph', 'Python3']
0
count-subtrees-with-max-distance-between-cities
Node Level DP
node-level-dp-by-fredzqm-5lvf
Code\njava []\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n Node[] nodes = new Node[n];\n for (int i
fredzqm
NORMAL
2024-11-16T18:24:10.254264+00:00
2024-11-16T18:24:10.254320+00:00
6
false
# Code\n```java []\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n Node[] nodes = new Node[n];\n for (int i = 0; i < n; i++) {\n nodes[i] = new Node(i+1);\n }\n for (int[] e : edges) {\n nodes[e[0]-1].children.add(nodes[e[1]-1]);\n nodes[e[1]-1].children.add(nodes[e[0]-1]);\n }\n int[] res = new int[n - 1];\n for (Node x: nodes) {\n for (Map.Entry<Size, Integer> e : x.subtree().entrySet()) {\n if (e.getKey().span-1 >= 0) {\n res[e.getKey().span-1] += e.getValue();\n }\n }\n }\n return res;\n }\n\n static class Node {\n int i;\n List<Node> children = new ArrayList<>();\n boolean visited = false;\n Map<Size, Integer> subTree;\n\n Node(int i) {\n this.i = i;\n }\n\n // res[maxDis][depth] ==> number of subtree.\n public Map<Size, Integer> subtree() {\n if (subTree != null) {\n return subTree;\n }\n visited = true;\n Map<Size, Integer> freq = new HashMap<>();\n freq.put(new Size(0, 0), 1);\n for (Node c : children) {\n if (c.visited) {\n continue;\n }\n Map<Size, Integer> childFreq = c.subtree();\n Map<Size, Integer> newFreq = new HashMap<>(freq);\n for (Map.Entry<Size, Integer> e : freq.entrySet()) {\n for (Map.Entry<Size, Integer> ce : childFreq.entrySet()) {\n Size exist = e.getKey();\n Size child = ce.getKey();\n Size s = new Size(\n Math.max(Math.max(exist.span, child.span), exist.depth + child.depth + 1),\n Math.max(exist.depth, child.depth + 1));\n newFreq.put(s, newFreq.getOrDefault(s, 0) + e.getValue() * ce.getValue());\n }\n }\n freq = newFreq;\n }\n subTree = freq;\n System.out.printf("%d: %s\\n", i, freq);\n return freq;\n }\n }\n\n static class Size {\n int span, depth;\n\n public Size(int s, int d) {\n span = s;\n depth = d;\n }\n\n public boolean equals(Object o) {\n if (o instanceof Size) {\n Size s = (Size) o;\n return span == s.span && depth == s.depth;\n }\n return false;\n }\n\n public int hashCode() {\n return span + depth * 31;\n }\n\n public String toString() {\n return String.format("(%d, %d)", span, depth);\n }\n }\n}\n```
0
0
['Java']
0
count-subtrees-with-max-distance-between-cities
BFS + bitmask, iterating all subsets
bfs-bitmask-iterating-all-subsets-by-gau-10jq
Intuition\n Describe your first thoughts on how to solve this problem. \n- First thing to do for all questions is to check constraints. For this, n <= 16 meanin
gauravk_25
NORMAL
2024-11-05T19:02:34.437039+00:00
2024-11-05T19:49:17.502148+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- First thing to do for all questions is to check constraints. For this, $$n <= 16$$ meaning that total no of possible subtrees can be `$$2^N$$ which is ~$$10^5$$. This means a bruteforce way is on the cards\n- As the input is a tree, there\'s only a single fixed way to travel between given two nodes, meaning that the distance and path between nodes is fixed. Also, a catch is to figure out that we only need the nodes which are present on the path between start and end nodes, and not their sequence. \n- from above statement, it also follows that the path between any pair of nodes in a subtree must only go through nodes in that subtree, as by definition all nodes in a tree are connected. This can help to identify valid subtrees \n- only having 16 nodes gives the possibility to store each subtree/path in a single int value, saving a ton of space and time \nGenerate Note: anytime there\'s a limitation to max 64 values (no of nodes, size of array/string, etc), always think about storing any temporary data you need as bits on an integer. Works 90% of the time\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- convert the edge list into an adjacency list\n- Precomputing all paths is done using a modified BFS which keeps track of current node as well as all nodes that we have travelled across on the way. \nDistance between two nodes = no of nodes in the path - 1\n- We iterate over all possible subtrees. For each, we make sure that the subtree is valid by checking that the path for each pair of nodes only passes through the subtree. We calculate max distance between 2 nodes in the subtree and maintain that in the result array\n\n# Complexity\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- creating adjacency list takes $$O(N)$$\n- modifed BFS takes $$O(N * (E + N))$$ => $$O(N^2)$$ as for a tree $$E = N - 1$$\n- total subtrees = $$2^N $$. iterating over all pair of nodes in a subtree takes $$O(N^2)$$. So this step takes $$O(N^2*2^N)$$\n- final complexity = $$O(N + N^2 + N^2*2^N)$$ => $$O(N^2*2^N)$$\n# Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- adjacency list takes $$O(E)$$\n- path matrix takes $$O(N^2)$$\n- - final Complexity = $$O(N^2)$$\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> path(n, vector<int> (n, -1));\n vector<vector<int>> adjacency_list(n, vector<int> {});\n vector<int> result(n - 1, 0);\n\n for(int i=0;i<edges.size();i++) {\n int x = edges[i][0] - 1, y = edges[i][1] - 1;\n adjacency_list[x].push_back(y);\n adjacency_list[y].push_back(x);\n }\n\n for(int i=0;i<n;i++) {\n vector<bool> seen(n, false);\n queue<vector<int>> q;\n q.push(vector<int> {i, 1 << i});\n while(!q.empty()) {\n for(int j=q.size();j>0;j--){\n int curr = q.front()[0], curr_nodes = q.front()[1];\n q.pop();\n\n if (seen[curr]) continue;\n seen[curr] = true, path[i][curr] = curr_nodes;\n for(int next : adjacency_list[curr]) {\n if (!seen[next]) q.push(vector<int> {next, curr_nodes | (1 << next)});\n }\n }\n }\n }\n\n for(int tree=0;tree<(1 << n);tree++) {\n int max_dist = 0;\n bool valid_tree = true;\n for(int n1=0;n1<n;n1++) {\n if (!(tree & (1 << n1))) continue;\n for(int n2=0;n2<n;n2++) {\n if (!(tree & (1 << n2))) continue;\n if ((tree & path[n1][n2]) != path[n1][n2]) {\n valid_tree = false;\n break;\n }\n max_dist = max(max_dist, __builtin_popcount(path[n1][n2]) - 1);\n }\n if (!valid_tree) break;\n }\n\n if (valid_tree && max_dist > 0) {\n result[max_dist - 1]++;\n }\n }\n\n return result;\n }\n};\n```
0
0
['Breadth-First Search', 'Bitmask', 'C++']
0
count-subtrees-with-max-distance-between-cities
A O(2^n*nlogn) solution Bitmask to find all possibilities and the final diameter of the graph.
a-o2nnlogn-solution-bitmask-to-find-all-f3t2j
Intuition\nWe will check all possibilities of picking up a subset of nodes.\nNow we will call the find diameter fn for finding the diameter which will use a pri
prime_bits
NORMAL
2024-11-02T14:40:00.996450+00:00
2024-11-02T14:40:00.996486+00:00
5
false
# Intuition\nWe will check all possibilities of picking up a subset of nodes.\nNow we will call the find diameter fn for finding the diameter which will use a priority_queue to maintain all the max depths from that node.\nSo the first and the runnerUp will give the max diameter of that subset.\nWe will mark visited with the help of mask as well.\nIf the mask is not 0 we will discard that subset from being counted.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> parent;\n int findParent(int u) {\n if(parent[u] == -1)return u;\n return findParent(parent[u]);\n }\n void unite(int u, int v) {\n int parA = findParent(u), parB = findParent(v);\n parent[parB] = parA;\n }\n int findDiameter(vector<int> adj[], int root, int &mask, int &maxDiam) {\n // cout<<root<<endl;\n mask ^= (1<<(root-1));\n priority_queue<int> distances;\n for(auto child:adj[root]) {\n if(!((mask>>(child-1))&1))continue;\n // cout<<child<<" "<<root<<endl;\n distances.push(findDiameter(adj, child, mask, maxDiam)+1);\n }\n int topDi = distances.empty()?0:distances.top();\n if(!distances.empty())distances.pop();\n int runnerUpDi = distances.empty()?0:distances.top();\n maxDiam = max(maxDiam, topDi+runnerUpDi);\n // cout<<topDi<<" "<<runnerUpDi<<" "<<maxDiam<<" "<<root<<endl;\n return topDi;\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<int> adj[n+1];\n int degrees[n+1];\n memset(degrees, 0, sizeof degrees);\n for(auto edge:edges) {\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n degrees[edge[1]]++;\n }\n\n vector<int> distancesMap(n-1);\n for(int i=3; i < (1<<n); i++) {\n int maxDistance = 0;\n int root = 0;\n int mask = i;\n int j = mask;\n while(j) {\n if((j&1))break; \n j>>=1;\n root++;\n }\n if(root+1<=n)\n findDiameter(adj, root+1, mask, maxDistance);\n if(maxDistance>0 && mask == 0)\n distancesMap[maxDistance-1]++;\n\n // if(__builtin_popcount(i) == 2)\n // cout<<i<<" "<<root<<" "<<mask<<" "<<maxDistance<<endl;\n }\n return distancesMap;\n }\n};\n```
0
0
['C++']
0
count-subtrees-with-max-distance-between-cities
Diameter of every mask
diameter-of-every-mask-by-theabbie-5p5p
\nclass Solution:\n def diameter(self, graph, root):\n n = len(graph)\n res = 0\n def d(i, p):\n nonlocal res\n s
theabbie
NORMAL
2024-10-24T05:51:23.842134+00:00
2024-10-24T05:52:25.126567+00:00
4
false
```\nclass Solution:\n def diameter(self, graph, root):\n n = len(graph)\n res = 0\n def d(i, p):\n nonlocal res\n s = 1\n a = b = 0\n mx = 0\n for j in graph[i]:\n if j == p:\n continue\n h, cs = d(j, i)\n s += cs\n mx = max(mx, h)\n t, a, b = sorted([h, a, b])\n res = max(res, a + b)\n return mx + 1, s\n d, size = d(root, -1)\n return res, size\n \n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n res = [0 for _ in range(n - 1)]\n for mask in range(1, 1 << n):\n graph = [[] for _ in range(n)]\n for u, v in edges:\n if mask & (1 << (u - 1)) and mask & (1 << (v - 1)):\n graph[u - 1].append(v - 1)\n graph[v - 1].append(u - 1)\n d, size = self.diameter(graph, min(i for i in range(n) if mask & (1 << i)))\n if d > 0 and size == mask.bit_count():\n res[d - 1] += 1\n return res\n```
0
0
['Python']
0
count-subtrees-with-max-distance-between-cities
1617. Count Subtrees With Max Distance Between Cities.cpp
1617-count-subtrees-with-max-distance-be-qlss
Code\n\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> graph(n);\n
202021ganesh
NORMAL
2024-10-05T09:51:13.004468+00:00
2024-10-05T09:51:13.004503+00:00
1
false
**Code**\n```\nclass Solution {\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<vector<int>> graph(n);\n for (auto& e : edges) {\n graph[e[0]-1].push_back(e[1]-1);\n graph[e[1]-1].push_back(e[0]-1);\n }\n vector<int> ans(n - 1, 0);\n for (int state = 1; state < (1 << n); state++) {\n int d = maxDistance(state, graph, n);\n if (d > 0) ans[d - 1] += 1;\n }\n return ans;\n } \n int maxDistance(int state, vector<vector<int>>& graph, int n) {\n int anyNode = 0, cntCity = 0;\n for (int i = 0; i < n; i++) if ((state >> i) & 1) {\n anyNode = i;\n cntCity += 1;\n }\n auto [farthestNode, _, visitedSize] = bfs(anyNode, state, graph, n);\n if (visitedSize < cntCity) return 0; \n auto [_ig1, dist, _ig2] = bfs(farthestNode, state, graph, n);\n return dist;\n } \n tuple<int, int, int> bfs(int src, int state, vector<vector<int>>& graph, int n) {\n unordered_set<int> visited{src};\n queue<pair<int,int>> q;\n q.push({src, 0});\n int farthestNode = -1, farthestDist = 0;\n while(!q.empty()){\n auto [u, d] = q.front(); q.pop();\n farthestNode = u, farthestDist = d;\n for (int v : graph[u]){\n if (visited.find(v) == visited.end() && (state >> v) & 1){\n q.push({v, d + 1});\n visited.insert(v);\n }\n }\n }\n return make_tuple(farthestNode, farthestDist, visited.size());\n }\n};\n```
0
0
['C']
0
count-subtrees-with-max-distance-between-cities
C# Brute Force Solution with Enumeration
c-brute-force-solution-with-enumeration-j84pz
Intuition\n Describe your first thoughts on how to solve this problem. To solve the problem of counting subtrees where the maximum distance between any two citi
GetRid
NORMAL
2024-08-27T15:13:32.517858+00:00
2024-08-27T15:13:32.517894+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->To solve the problem of counting subtrees where the maximum distance between any two cities is equal to \'d\', we can use a brute-force approach given the constraints that n is less than or equal to 15.\n\n___\n\n# Approach\n<!-- Describe your approach to solving the problem. -->// Graph Initialization: We initialize the graph as an adjacency list.\n// Mask Enumeration: We enumerate all possible subsets of cities using a bitmask approach. Each bit in the \n// mask represents whether a city is included in the subset.\n// Connected Subtrees: We check if a subset of cities forms a connected component using a BFS-based \n// IsConnected method.\n// Maximum Distance Calculation: For each connected subtree, we calculate the maximum distance using BFS in\n// the GetMaxDistance method.\n// Result Accumulation: We accumulate the count of subtrees with each possible maximum distance.\n___\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(2^n x n^2).\n____\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n^2).\n___\n\n# Code\n```csharp []\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Solution {\n public int[] CountSubgraphsForEachDiameter(int n, int[][] edges) {\n var graph = new List<int>[n + 1];\n for (int i = 1; i <= n; i++) {\n graph[i] = new List<int>();\n }\n\n foreach (var edge in edges) {\n graph[edge[0]].Add(edge[1]);\n graph[edge[1]].Add(edge[0]);\n }\n\n int[] result = new int[n - 1];\n\n for (int mask = 1; mask < (1 << n); mask++) {\n List<int> nodes = new List<int>();\n for (int i = 0; i < n; i++) {\n if ((mask & (1 << i)) != 0) {\n nodes.Add(i + 1);\n }\n }\n\n if (IsConnected(graph, nodes)) {\n int maxDist = GetMaxDistance(graph, nodes);\n if (maxDist > 0 && maxDist < n) {\n result[maxDist - 1]++;\n }\n }\n }\n\n return result;\n }\n\n private bool IsConnected(List<int>[] graph, List<int> nodes) {\n var visited = new HashSet<int>();\n Queue<int> queue = new Queue<int>();\n queue.Enqueue(nodes[0]);\n visited.Add(nodes[0]);\n\n while (queue.Count > 0) {\n int node = queue.Dequeue();\n foreach (int neighbor in graph[node]) {\n if (nodes.Contains(neighbor) && !visited.Contains(neighbor)) {\n visited.Add(neighbor);\n queue.Enqueue(neighbor);\n }\n }\n }\n\n return visited.Count == nodes.Count;\n }\n\n private int GetMaxDistance(List<int>[] graph, List<int> nodes) {\n int maxDist = 0;\n foreach (int node in nodes) {\n var dist = BFS(graph, node, nodes);\n maxDist = Math.Max(maxDist, dist);\n }\n return maxDist;\n }\n\n private int BFS(List<int>[] graph, int start, List<int> nodes) {\n var dist = new Dictionary<int, int>();\n foreach (int node in nodes) {\n dist[node] = -1;\n }\n\n Queue<int> queue = new Queue<int>();\n queue.Enqueue(start);\n dist[start] = 0;\n\n int maxDist = 0;\n\n while (queue.Count > 0) {\n int node = queue.Dequeue();\n foreach (int neighbor in graph[node]) {\n if (nodes.Contains(neighbor) && dist[neighbor] == -1) {\n dist[neighbor] = dist[node] + 1;\n maxDist = Math.Max(maxDist, dist[neighbor]);\n queue.Enqueue(neighbor);\n }\n }\n }\n\n return maxDist;\n }\n}\n```
0
0
['Tree', 'Enumeration', 'C#']
0
count-subtrees-with-max-distance-between-cities
C++ dpWithBitMask Step By Step Explanation 90% Faster O(N*2^N)
c-dpwithbitmask-step-by-step-explanation-fm06
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
_Just__Chill
NORMAL
2024-08-16T17:30:42.649728+00:00
2024-08-16T17:30:42.649761+00:00
9
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)$$ -->O(n*2^n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(2^n)\n\n# Code\n```\nclass Solution {\npublic:\n //Function to find Distance of all nodes from a given node.->o(n)\n //This function is called for each node.->o(n*n)\n vector<int>findDistance(vector<vector<int>>&adj,int node){\n int n=adj.size();\n vector<int>ans(n);\n ans[node]=0;\n queue<pair<int,int>>q;\n q.push({node,-1});\n while(!q.empty()){\n int curr_node=q.front().first;\n int parent=q.front().second;\n q.pop();\n for(auto &j:adj[curr_node]){\n if(j!=parent){\n ans[j]=ans[curr_node]+1;\n q.push({j,curr_node});\n }\n }\n }\n return ans;\n }\n //Function To check that the nodes present in mask forms a Subtree.->o(setBits in mask) for calls + o(n) for adjacency list in total.\n bool isValidSubTree(vector<vector<int>>&adj,int originalMask,int &mask,int curr_node){\n mask=mask|(1<<curr_node);\n if(mask==originalMask)return true;\n for(auto &j:adj[curr_node]){\n if((originalMask&(1<<j)) && (!(mask&(1<<j)))){\n if(isValidSubTree(adj,originalMask,mask,j)){\n return true;\n }\n }\n }\n return false;\n\n } \n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n \n //Graph->o(n+E),where E=n-1;\n vector<vector<int>>adj(n);\n for(int i=0;i<n-1;i++){\n int u=edges[i][0];\n int v=edges[i][1];\n adj[u-1].push_back(v-1);\n adj[v-1].push_back(u-1);\n }\n //Calculating a 2D (n*n) distance matrix->o(n*n)\n vector<vector<int>>dist(n);\n for(int i=0;i<n;i++){\n dist[i]=findDistance(adj,i);\n }\n vector<int>dp(1<<n);\n vector<bool>mark(1<<n);\n //O(n*2^n)\n for(int mask=1;mask<(1<<n);mask++){\n int bits=__builtin_popcount(mask);\n //There must be two nodes to get distance 1.\n if(bits<2){\n continue;\n }\n int curr_Mask=0;\n int lastSetbit=0;\n for(int j=0;j<n;j++){\n if(mask&(1<<j)){\n lastSetbit=j;\n break;\n }\n }\n //if mask is subtree mark it.\n if(isValidSubTree(adj,mask,curr_Mask,lastSetbit)){\n mark[mask]=1;\n }\n //check max Distance for Subtree ...using dp->\n int maxDistance=0;\n //just remove a node ans for remaining combination node is precalculated\n if((mask&(1<<lastSetbit))){\n int newMask=(mask^(1<<lastSetbit));\n maxDistance=max(dp[newMask],maxDistance);\n // check the distance of all nodes due to removed node and calculate the final ans\n for(int k=0;k<n;k++){\n if(newMask&(1<<k)){\n maxDistance=max(maxDistance,dist[lastSetbit][k]);\n }\n } \n }\n \n dp[mask]=maxDistance;\n }\n vector<int>result(n-1);\n //if mask is validSubTree and maxDistance is AtLeast 1 .Then ,store it in result\n for(int mask=1;mask<(1<<n);mask++){\n if(dp[mask] && mark[mask]){\n result[dp[mask]-1]++;\n } \n }\n return result;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Bitmask', 'C++']
0
count-subtrees-with-max-distance-between-cities
Brute force - Tree diameter with DFS
brute-force-tree-diameter-with-dfs-by-as-jbui
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
ashutoshdayal
NORMAL
2024-08-11T19:17:20.486430+00:00
2024-08-11T19:17:20.486453+00:00
19
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.2^n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nint nodecnt;\nint depth[15];\nvoid dfs(int i, int par, int dep, vector<vector<int>> &g, int nodes) {\n if (!((nodes>>i)&1)) return;\n depth[i]=dep;\n nodecnt++;\n for (auto &v:g[i]) if (v!=par)\n dfs(v,i,dep+1,g,nodes);\n}\n\nclass Solution {\npublic:\n//O(n.2^n)\nvector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n vector<int> ans(n-1,0);\n vector<vector<int>> g;g.resize(n);\n for (auto &ed:edges) { g[ed[0]-1].push_back(ed[1]-1); g[ed[1]-1].push_back(ed[0]-1); }\n for (int mask=0;mask<(1<<n);mask++) {\n // for (auto &_:nodes)cout<<_<<\' \';cout<<endl;\n int tot=__builtin_popcount(mask);\n if (!tot) continue;\n nodecnt=0;\n memset(depth,-1,sizeof(depth));\n\n int st=0;\n while (!((mask>>st)&1)) st++;\n\n dfs(st,-1,0,g,mask);\n if (nodecnt==tot) { //connected\n // for (auto &_:nodes)cout<<_+1<<\' \';cout<<"\\t\\t";\n // for (int i=0;i<n;i++) cout<<depth[i]<<\' \';cout<<"\\t";\n int max_dep_node=0;\n for (int i=1;i<n;i++) if (depth[i]>depth[max_dep_node])\n max_dep_node=i;\n // cout<<max_dep_node<<endl;\n // assert(nodes.find(max_dep_node)!=nodes.end());\n\n memset(depth,-1,sizeof(depth));\n dfs(max_dep_node,-1,0,g,mask);\n max_dep_node=0;\n for (int i=1;i<n;i++) if (depth[i]>depth[max_dep_node])\n max_dep_node=i;\n\n // cout<<depth[max_dep_node]<<endl;\n\n if (depth[max_dep_node]) ans[depth[max_dep_node]-1]++;\n }\n }\n return ans;\n}\n};\n```
0
0
['C++']
0
count-subtrees-with-max-distance-between-cities
BFS + tree DP
bfs-tree-dp-by-jackyhe07-tlbe
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nuse BFS\n1) add each si
jackyhe07
NORMAL
2024-08-09T02:10:36.269087+00:00
2024-08-09T02:10:36.269106+00:00
51
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nuse BFS\n1) add each single node into the queue\n2) each step , extend one more node to get a new tree\n3) for each tree, use DP with tree to get the max distance\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 countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n lookup = [[] for _ in range(n+1)]\n for u, v in edges:\n lookup[u].append(v)\n lookup[v].append(u)\n\n def get_max_distance(tree):\n root = 0\n for i in range(1, n+1):\n if (1 << i) & tree:\n root = i\n break\n distance = 0\n fathers = set([root])\n def dp(node): # get max path length ending with this node\n nonlocal distance\n childs = []\n for next in lookup[node]:\n if (1 << next) & tree:\n if next in fathers:\n continue\n fathers.add(next)\n childs.append(dp(next))\n if len(childs) == 0:\n return 0\n if len(childs) == 1:\n distance = max(distance, childs[0] + 1)\n return childs[0] + 1\n \n childs.sort()\n # get max path pass through this node\n distance = max(distance, childs[-1] + childs[-2] + 2)\n return childs[-1] + 1\n\n dp(root)\n return distance\n \n q = deque()\n visited = set()\n for i in range(1, n+1):\n q.append(1 << i)\n visited.add(1 << i)\n res = [0 for _ in range(n - 1)]\n while q:\n cur = q.popleft()\n if cur.bit_count() > 1:\n res[get_max_distance(cur)-1] += 1\n\n for u, v in edges:\n uin, vin = (1 << u) & cur, (1 << v) & cur\n if uin and vin:\n continue\n if (not uin) and (not vin):\n continue\n if uin:\n next = cur | (1 << v)\n if next not in visited:\n visited.add(next)\n q.append(next)\n elif vin:\n next = cur | (1 << u)\n if next not in visited:\n visited.add(next)\n q.append(next)\n\n return res\n\n```
0
0
['Python3']
0
count-subtrees-with-max-distance-between-cities
C++ || Bitmasking || Floyd-Warshall
c-bitmasking-floyd-warshall-by-akash92-bok5
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to count the number of subgraphs (connected subtrees) in a tree for each po
akash92
NORMAL
2024-08-03T11:12:08.317835+00:00
2024-08-03T11:12:08.317892+00:00
36
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to count the number of subgraphs (connected subtrees) in a tree for each possible diameter. A diameter of a tree is the longest shortest path between any two nodes in that tree. To achieve this, we need to:\n\n1. Identify all possible subgraphs.\n2.\tCheck if each subgraph is a valid tree.\n3.\tCalculate the diameter of each valid tree.\n4.\tCount how many trees have each possible diameter.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tInitialize the Distance Matrix:\n\t\u2022\tCreate a distance matrix dist with large initial values to represent the maximum possible distances between nodes.\n\t\u2022\tSet the distances for the direct edges given in the input to 1.\n2.\tCompute All-Pairs Shortest Paths (Floyd-Warshall Algorithm):\n\t\u2022\tUpdate the distance matrix to store the shortest paths between all pairs of nodes using the Floyd-Warshall algorithm.\n3.\tFunction to Evaluate Subgraph Validity and Diameter (f function):\n\t\u2022\tFor each possible subset of nodes (represented by a bitmask), determine if it forms a valid tree.\n\t\u2022\tIf valid, calculate the maximum distance (diameter) in this subset.\n4.\tCount Subgraphs for Each Diameter:\n\t\u2022\tIterate through all possible subsets of nodes.\n\t\u2022\tUse the f function to determine if each subset is a valid tree and to calculate its diameter.\n\t\u2022\tIncrement the count for the corresponding diameter if the subset is a valid tree.\n\n# Complexity\n- Time complexity: $$O(n^3+2^n*n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nvector<vector<int>> dist;\nprivate:\n int f(int mask, int n){\n int node = 0;\n int edge = 0;\n int maxi = 0;\n\n for(int i=0; i<n; i++){ // checking if i\'th node is included in subset\n if(((mask>>i)&1)==1){\n node++;\n for(int j=i+1; j<n; j++){\n if(((mask>>j)&1)==1){ // going to all the next included nodes and calculating diameter\n if(dist[i][j]==1) edge++;\n maxi = max(maxi, dist[i][j]);\n }\n }\n }\n }\n\n // if complete subtree forms return maximum distance, else return -1\n if(node==edge+1) return maxi;\n else return -1;\n }\npublic:\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n\n dist = vector<vector<int>>(15, vector<int>(15, 1e9));\n for(auto it: edges){\n dist[it[0]-1][it[1]-1] = dist[it[1]-1][it[0]-1] = 1;\n }\n\n // finding minimum distance between each pair of cities\n for(int k=0; k<n; k++){\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]);\n }\n }\n }\n\n vector<int> ans(n-1,0);\n\n for(int i=0; i<(1<<n); i++){\n int d = f(i,n);\n if(d>0){\n ans[d-1]++;\n }\n }\n\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'Bit Manipulation', 'Tree', 'Enumeration', 'Bitmask', 'C++']
0
count-subtrees-with-max-distance-between-cities
Bitmask + DFS + Recursion
bitmask-dfs-recursion-by-coding_jod-kza7
Intuition\n Describe your first thoughts on how to solve this problem. \nYou have to build all possible trees and then do a dfs on every tree to find the diamet
coding_jod
NORMAL
2024-07-28T16:30:33.928015+00:00
2024-07-28T16:30:33.928039+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou have to build all possible trees and then do a dfs on every tree to find the diameter of the tree.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI took a bitmask for the allowed variable, if ith bit is set it means my current tree has ith node, now i run a simple dfs by visiting only the allowed nodes and caluclating the diameter of the tree thereby \nAlso the visited bitmask has been used to maintain that infinite loop is not created, because the edges are bidirectional hence going back to the parent is not encouraged.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(2^n * n * n) which makes it ~ 32000 * 225 ~ 1e5\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n*n);\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> adj;\n int dfs(int node,int allowed,int& ans,int& vis){\n if(!(allowed & (1<<(node)))){\n for(int j=1;j<16;j++) if(allowed & (1<<(j))) {node=j; break;}\n }\n int depth1=0,depth2=0;\n // vis[node]=1;\n vis=(vis | (1<<(node)));\n for(auto x: adj[node]){\n if((allowed & (1<<(x))) && !(vis & (1<<(x)))){\n int xx=dfs(x,allowed,ans,vis);\n if(xx>depth1) {\n depth2=depth1;\n depth1=xx;\n }\n else if(xx>depth2) depth2=xx;\n }\n }\n ans=max(ans,depth1+depth2);\n return max(depth1,depth2)+1;\n }\n bool check(int allow){\n int allowed=allow;\n int root=-1;\n for(int i=1;i<16;i++) if(allowed & (1<<i)) root=i;\n if(root==-1) return false;\n stack<int> st;\n st.push(root);\n while(!st.empty()){\n int node=st.top();\n st.pop();\n allowed=(allowed & ~(1<<(node)));\n for(auto x: adj[node]) \n if(allowed & (1<<x)) st.push(x);\n }\n for(int i=0;i<16;i++) if(allowed & (1<<i)) return 0;\n return 1;\n }\n void solve(int i,int n,int allowed,vector<int>& res){\n if(i>n) {\n int ans=0;\n if(check(allowed)){\n // vector<int> vis(n+1,0);\n int vis=0;\n dfs(1,allowed,ans,vis);\n res[ans]++;}\n return;\n }\n solve(i+1,n,allowed,res);\n allowed+=(1<<i);\n solve(i+1,n,allowed,res);\n }\n vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n adj.resize(n+1);\n for(auto edge: edges) \n {\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n }\n // vector<int> allowed(n+1,0);\n int allowed=0;\n vector<int> res(n,0);\n solve(1,n,allowed,res);\n vector<int> finalres;\n for(int i=1;i<n;i++)\n finalres.push_back(res[i]);\n return finalres;\n }\n}; \n```
0
0
['C++']
0
count-subtrees-with-max-distance-between-cities
JAVA SOLUTION
java-solution-by-danish_jamil-c1k4
Intuition\n\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- Tim
Danish_Jamil
NORMAL
2024-07-08T06:25:36.660617+00:00
2024-07-08T06:25:36.660658+00:00
21
false
# Intuition\n![images.jfif](https://assets.leetcode.com/users/images/2a46905d-e3ed-49ac-84d1-a846842c0264_1720419932.952098.jpeg)\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 {\n\n List<Integer>[] tree, subTree;\n int subTreeRoot, maxPath;\n boolean[] inStack; // do not allow to travel upwards in the rooted tree\n int[] ans;\n\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n buildTree(n, edges);\n ans = new int[n - 1];\n solve(0);\n return ans;\n }\n\n private void buildTree(int n, int[][] edges) {\n tree = new List[n];\n subTree = new List[n];\n inStack = new boolean[n];\n for (int i = 0; i < n; ++i) {\n tree[i] = new ArrayList<>();\n subTree[i] = new ArrayList<>();\n }\n for (int[] e : edges) {\n tree[e[0] - 1].add(e[1] - 1);\n tree[e[1] - 1].add(e[0] - 1);\n }\n }\n\n private void solve(int i) {\n subTreeRoot = i;\n inStack[i] = true;\n buildSubTree(0, 0, Collections.singletonList(i), new ArrayList<>());\n for (int e : tree[i]) {\n if (inStack[e]) {\n continue;\n }\n solve(e);\n }\n }\n\n private void buildSubTree(int i, int j, List<Integer> fronteer, List<Integer> next) {\n if (i >= fronteer.size()) {\n buildNextLevel(next);\n return;\n }\n int curr = fronteer.get(i);\n if (j >= tree[curr].size()) {\n buildSubTree(i + 1, 0, fronteer, next);\n } else {\n int succ = tree[curr].get(j);\n if (inStack[succ]) {\n buildSubTree(i, j + 1, fronteer, next);\n return;\n }\n inStack[succ] = true;\n next.add(succ);\n subTree[curr].add(succ);\n buildSubTree(i, j + 1, fronteer, next);\n next.remove(next.size() - 1);\n subTree[curr].remove(subTree[curr].size() - 1);\n buildSubTree(i, j + 1, fronteer, next);\n inStack[succ] = false;\n }\n }\n\n private void buildNextLevel(List<Integer> next) {\n if (next.isEmpty()) { // subTree is done, add it to the answer\n maxPath = 0;\n computeMaxPath(subTreeRoot);\n if (maxPath > 1) {\n ++ans[maxPath - 2];\n }\n } else {\n buildSubTree(0, 0, next, new ArrayList<>());\n }\n }\n\n private int computeMaxPath(int i) {\n int max = 0, prevMax = 0;\n for (int child : subTree[i]) {\n int h = computeMaxPath(child);\n if (h >= max) {\n prevMax = max;\n max = h;\n } else {\n prevMax = Integer.max(prevMax, h);\n }\n }\n maxPath = Integer.max(maxPath, prevMax + max + 1);\n return max + 1;\n }\n}\n```
0
0
['Java']
0