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 ...
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(...
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)$$ --...
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 man...
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://leetco...
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 parenthes...
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...
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...
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...
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 o...
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`...
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 rem...
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`...
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# A...
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\...
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 p...
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 fo...
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 fo...
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 f...
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 ...
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()) a...
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 ...
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 ...
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...
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 open...
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)$$ --...
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 ...
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()==\'(\')...
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) ,...
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...
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...
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...
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 ...
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 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, ...
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, ...
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 g...
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 ma...
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 dis...
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 pai...
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 ...
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 ...
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...
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 indexin...
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-...
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#defin...
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 ...
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 + tr...
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:\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 ...
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 v...
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 need...
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...
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 ...
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```\ncla...
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 ...
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 co...
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 whi...
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 edg...
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 `...
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 ...
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 di...
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[]...
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...
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 combin...
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 ...
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++;\...
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 `visit...
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 m...
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...
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
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][...
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 ...
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 ...
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)...
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]]) ->...
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 kn...
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)...
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, e...
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(sel...
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.par...
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++) { ...
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. ...
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 `...
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 y...
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 fro...
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...
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, th...
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 wit...
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, ...
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>...
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 y...
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...
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<...
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#...
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 ...
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 m...
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...
0
0
['Java']
0