Minimum Height Trees - Leetcode 310 - Python

  Рет қаралды 21,691

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 52
@alexeyfv
@alexeyfv 7 ай бұрын
I was only able to implement a brute force solution, but only 67 out of 71 test cases passed (got time limit exception). 😁Thanks for the video.
@3227998
@3227998 Ай бұрын
Decreasing the number of edges is similar to Kahn's algorithm (topological sort) where indegree of a node is decreased as we traverse the tree.
@harshitdandelia4663
@harshitdandelia4663 26 күн бұрын
But doesn't that only work with Directed graphs?
5 ай бұрын
Perhaps slightly simpler (more familiar BFS) impl where we can get rid of the layer traversal technique. At the end of the while loop, all root will have the highest layer value (since they're the last layer) 😃 // Initialize layers with -1, except leaves layers are 0. int max_layer = 0; while (!q.empty()) { int u = q.front(); q.pop(); link[u]--; for (int v : adj[u]) { link[v]--; // Here, one of u's neighbors v just turned into a leaf node after u is removed. if (link[v] == 1 && layers[v] == -1) { layers[v] = layers[u] + 1; max_layer = max(max_layer, layers[v]); q.push(v); } } } vector res; for (int i = 0; i < n; i++) { if (layers[i] == max_layer) { res.push_back(i); } }
@sankhadip_roy
@sankhadip_roy 7 ай бұрын
code: class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n==1: return [0] adj = defaultdict(list) for n1,n2 in edges: adj[n1].append(n2) adj[n2].append(n1) edgecount = {} leaves = deque() for s, nei in adj.items(): if len(nei)==1: leaves.append(s) edgecount[s]=len(nei) while leaves: if n
@bhuvan9956
@bhuvan9956 7 ай бұрын
Thanks for this. Please do daily LCs and Contest please.
@singletmat5172
@singletmat5172 7 ай бұрын
I liked the note about the length and how other languages would calculate the length. With so much python sugar, we forget how a similar code would break in Java or C.
@gary1614
@gary1614 7 ай бұрын
Great video as always! One thing that's worth mentioning is that if n
@KaranBulani
@KaranBulani 7 ай бұрын
was thinking same
@bellxlilies9913
@bellxlilies9913 7 ай бұрын
Yes, if the n
@sallaklamhayyen9876
@sallaklamhayyen9876 Ай бұрын
great explanation. thank you so much
@_N_E_E_R_A_J_
@_N_E_E_R_A_J_ 7 ай бұрын
I solved it using re-rooting. But this "Removing leaf nodes" solution is very amazing. I didn't thought of that. Thank you so much!💖
@yang5843
@yang5843 7 ай бұрын
Whenever I struggle with daily Leetcode problems, I turn to Neetcode
@shreehari2589
@shreehari2589 7 ай бұрын
Ok
@yang5843
@yang5843 7 ай бұрын
For the edge case, you could check if length of neighbours is 0 or 1, then it will pass the edge case, without having to create an seperate check for the edge case
@EduarteBDO
@EduarteBDO 7 ай бұрын
This question was super hard, first I tried solving it with DP with memoization, it gave me TLE on test 70 I think
@chaitanyasharma6270
@chaitanyasharma6270 7 ай бұрын
Kahn's algorithm as intuition for this question. topsort(remove) where indegree ==1
@chrysco
@chrysco 7 ай бұрын
No need to check if n==1: return[0], we can return [0] after the while loop and it will work fine.
@chandrikasaha6301
@chandrikasaha6301 Ай бұрын
Please tell me one thing, why for loop is required here? why only popleft() does not work here
@AmanjotSingh-rj7ox
@AmanjotSingh-rj7ox 2 ай бұрын
Brute : class Solution { public List findMinHeightTrees(int n, int[][] edges) { // Step 1: Initialize the adjacency matrix with large values int[][] matrix = new int[n][n]; for (int[] i : matrix) Arrays.fill(i, 100000); // Large number to indicate no direct path // Step 2: Set the diagonal to 0 and fill in the edges (distance 1 for connected nodes) for (int i = 0; i < n; i++) matrix[i][i] = 0; for (int[] e : edges) { matrix[e[0]][e[1]] = 1; matrix[e[1]][e[0]] = 1; // Undirected graph, so both directions are set } // Step 3: Floyd-Warshall algorithm to calculate shortest paths between all pairs for (int k = 0; k < n; k++) { for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { matrix[row][col] = Math.min(matrix[row][col], matrix[row][k] + matrix[k][col]); } } } // Print the resulting distance matrix (for debugging purposes) System.out.print(Arrays.deepToString(matrix)); // Step 4: Find the minimum height trees // For each node, calculate the maximum distance to any other node (its "height") int[] maxDist = new int[n]; int minHeight = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { maxDist[i] = Math.max(maxDist[i], matrix[i][j]); } minHeight = Math.min(minHeight, maxDist[i]); } // Step 5: Collect all nodes whose maximum distance is equal to the minimum height List result = new ArrayList(); for (int i = 0; i < n; i++) { if (maxDist[i] == minHeight) { result.add(i); } } return result; } }
@MP-ny3ep
@MP-ny3ep 7 ай бұрын
Thank you so much for the daily. Really helps a lot.
@DBagg-zz4ip
@DBagg-zz4ip 7 ай бұрын
Okay. At first I thought it was just BFS from the leaves until you have 2 or 1 left. Lots of tests failed. The whole subtracting edges thing went over my head. Second explanation was easy to get though I haven't tried it yet.
@SmoothCode
@SmoothCode Ай бұрын
why do we return list(leaves) when n
@phanthe3471
@phanthe3471 7 ай бұрын
it takes me over 15 minutes to be clear the requirement,and until i finished the solution, it takes more than 1 hour.
@pixusru
@pixusru 7 ай бұрын
You’re not supposed to come up with requirements and approach on the spot. You must know every possible problem or pattern by heart, because many do, so you’re looking bad compared to them. Sorry, that’s the game.
@kumarc4853
@kumarc4853 7 ай бұрын
@@pixusru true, the people who post this arent solving this live and for the first time either. So solve as many as you can and spot patterns, recognize general strategies, things to think about when blocked etc
@sophiophile
@sophiophile 6 ай бұрын
​@@pixusru Tell that to interviewers at FAANG companies :(. I have spent a long time preparing for the code portion of an interview w/ one tomorrow (even though I already have another role essentially secured as a backup). There's always going to be the chance that you just don't spot the optimal solution at that time, no matter how prepped you are. For example, most FAANG would not accept the solution coded up here and would require the second approach he described (since it is O(n) time, O(1) memory- while the first is O(n)/O(n))
@tekfoonlim4745
@tekfoonlim4745 7 ай бұрын
Hey Navdeep how are you? I love your leetcode explanations and your solutions! Gives me motivation to do more leetcode
@YuriiPalchynskyi
@YuriiPalchynskyi 7 ай бұрын
Proof why leaf nodes can't be a root of min path. Suppose exist a min path, where leaf node is a root A(leaf) - B(end) , the node A has one neighbor N and this neighbor has to be included into the path A-B , from this we can find a root with smaller path N-B
@ChiragVithlani
@ChiragVithlani 7 ай бұрын
This problem should be renamed from "Minimum Height Trees" to "Find the root". We can imagine like cutting leaf from all sides equally at same level. What is left is root ( can be two node or one ).
@omarr993
@omarr993 7 ай бұрын
edging to this rn
@MrSkyS-i5v
@MrSkyS-i5v 7 ай бұрын
Missed you buddy 😭
@Droid261
@Droid261 7 ай бұрын
Thank you, I needed this
@chandrikasaha6301
@chandrikasaha6301 Ай бұрын
Was trying Union join
@sophiophile
@sophiophile 6 ай бұрын
Can you do a video using Morris traversal?
@sanchitbajaj02
@sanchitbajaj02 7 ай бұрын
Is it ok if after watching an entire video, didn't get the solution considering I only have a basic knowledge of graphs and DFS
@hamirmahal
@hamirmahal 7 ай бұрын
Thanks for putting this up!
@impatientgaming9868
@impatientgaming9868 7 ай бұрын
Good one
@jand2861
@jand2861 7 ай бұрын
really cool stuff man, thanks for the content
@paritoshpandey7998
@paritoshpandey7998 Ай бұрын
can we say it's the middle of the diameter?
@srprawinraja4261
@srprawinraja4261 7 ай бұрын
Thanks 😊
@buckboot
@buckboot 7 ай бұрын
Thanks for this
@georgerussel
@georgerussel 6 ай бұрын
The brute force solution is still hard to do
@bhavasagar977
@bhavasagar977 7 ай бұрын
The second approach feels more intuitive for me...
@ish90917
@ish90917 7 ай бұрын
Is the time complexity of the code O(n) ?
@amitchoraria5737
@amitchoraria5737 7 ай бұрын
i think yeah should be O(n). but just want someone to confirm
@juanito1410
@juanito1410 7 ай бұрын
The algorithm here is called khan's algorithm and its TC will be O(V+E) where V is the number of vertices/nodes and E for the count of edges.
@jessicakoch2331
@jessicakoch2331 7 ай бұрын
omg i hate graph problems, I hope one day they become less intimidating
@deathbombs
@deathbombs 7 ай бұрын
Crazy hard
@Silquey
@Silquey 7 ай бұрын
neetcoede
@saarNurf
@saarNurf 18 күн бұрын
One would argue that the goal is to find the median(s) node(s) of the longest path of the graph, and this median(s) would be the root of the MHT. why? because the median will partition the longest path in such a way that the max(left_partition,right_partition) will result in the minimum partition possible, which allows us to minimize the longest path and therefore to achieve the MHT. any thoughts? @NeetCodeIO #neetcode
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 147 М.
Longest Ideal Subsequence - Leetcode 2370 - Python
28:02
NeetCodeIO
Рет қаралды 12 М.
How to have fun with a child 🤣 Food wrap frame! #shorts
0:21
BadaBOOM!
Рет қаралды 17 МЛН
310. Minimum Height Trees | BFS | Topological Sort | Graphs
24:47
Distribute Coins in Binary Tree - Leetcode 979 - Python
17:41
NeetCodeIO
Рет қаралды 17 М.
Rotating the Box - Leetcode 1861 - Python
15:14
NeetCodeIO
Рет қаралды 5 М.
Graph Valid Tree - Leetcode 261 - Python
14:11
NeetCode
Рет қаралды 103 М.
Microservices are Technical Debt
31:59
NeetCodeIO
Рет қаралды 642 М.
Unique Binary Search Trees II - Leetcode 95 - Python
12:51
NeetCodeIO
Рет қаралды 19 М.
Visualizing transformers and attention | Talk for TNG Big Tech Day '24
57:45
Diameter of a Binary Tree - Leetcode 543 - Python
15:34
NeetCode
Рет қаралды 237 М.