G-47. Kruskal's Algorithm - Minimum Spanning Tree - C++ and Java

  Рет қаралды 158,041

take U forward

take U forward

Жыл бұрын

GfG-Problem Link: bit.ly/3eLuYvH
C++/Java/Codes and Notes Link: takeuforward.org/data-structu...
DP Series: • Striver's Dynamic Prog...
SDE Sheet: takeuforward.org/interviews/s...
Check out our Website for curated resources:
Our Second Channel: / @striver_79
In case you are thinking to buy courses, please check below:
Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
Linkedin/Instagram/Telegram: linktr.ee/takeUforward
---------------------------------------------------------------------------------------------------------------------------

Пікірлер: 192
@takeUforward
@takeUforward Жыл бұрын
Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too,. Do follow me on Instagram: striver_79
@Mohini-rt4wu
@Mohini-rt4wu 4 ай бұрын
I am not getting what the M and N stands for, when you are calculating time complexities.
@KiranKumar-sb3ti
@KiranKumar-sb3ti Ай бұрын
understood
@coding8000
@coding8000 Жыл бұрын
you will be remembered in all three tenses i.e past, current, future., keep going bro, my power to you.
@SumitKeshariMCS
@SumitKeshariMCS Жыл бұрын
Understood each and every second of the video. Thanks Striver.
@raghavagrawal9240
@raghavagrawal9240 Жыл бұрын
Was waiting for the series to continue! Thanks
@cinime
@cinime Жыл бұрын
Understood! Super wonderful explanation as always, thank you!!
@averylazyandweirdhuman
@averylazyandweirdhuman Ай бұрын
Thanks Striver! I was solving a leetcode problem and unable to solve it then i saw the topic was Disjoint set and I watched these few videos and instantly recognized that the problem can be solved using Kruskal's Algorithm easily
@oqant0424
@oqant0424 Жыл бұрын
Understood! Super wonderful explanation❤
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
understood,great explanation
@sahillakhani1962
@sahillakhani1962 11 ай бұрын
well explained sir. Understood clearly!
@stith_pragya
@stith_pragya 7 ай бұрын
Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@mohammadahsan7873
@mohammadahsan7873 8 ай бұрын
Superb Explanations... ❤👏
@prasannasippa5962
@prasannasippa5962 Жыл бұрын
understood striver.... Thank you so much
@suryasingh2563
@suryasingh2563 Жыл бұрын
Fully understood bhaiya...
@kshitijmishra2716
@kshitijmishra2716 Жыл бұрын
when you said drivers code muje kuch yaad aaa gaya 😂😂🔥🔥 but yeah you are rider the dsa driver the one and only strive 😎😎
@aakashgoswami2356
@aakashgoswami2356 Жыл бұрын
bhai kehna kya chhata hai ?
@vishnubanjara5209
@vishnubanjara5209 Жыл бұрын
@@aakashgoswami2356 controversy ki baat kr rha h bhai vo but striver is best teacher for dsa learning
@studybits1604
@studybits1604 10 ай бұрын
@@vishnubanjara5209 i still didnt get it
@amantripathi4100
@amantripathi4100 Жыл бұрын
Bhai indeed the best teacher
@udaytewary3809
@udaytewary3809 Жыл бұрын
Understood bhaiya 🙏❤️
@ajaybabupatel1665
@ajaybabupatel1665 Жыл бұрын
understood, thanks raj
@pallavigkumaraswamy5874
@pallavigkumaraswamy5874 9 күн бұрын
Understood clearly!!!!
@abhishekkuntare4640
@abhishekkuntare4640 Жыл бұрын
Understood Raj bhaiyaa ❤❤
@user-fs8km9qc8f
@user-fs8km9qc8f Ай бұрын
very nice explanation
@suryasingh2563
@suryasingh2563 Жыл бұрын
Understood Bhaiya❣
@parshchoradia9909
@parshchoradia9909 Жыл бұрын
Understood Sir!
@UECAshutoshKumar
@UECAshutoshKumar 7 ай бұрын
Thank you sir 🙏
@anshulagarwal6682
@anshulagarwal6682 Жыл бұрын
Please also make video on dp on trees, heavy light decomposition.
@mugambo5505
@mugambo5505 Жыл бұрын
understood thanks sir ❣❣❣❣
@herculean6748
@herculean6748 Жыл бұрын
Thanks🙌
@UjjwalPratapSingh-hh6wu
@UjjwalPratapSingh-hh6wu Жыл бұрын
Understood 👍🏻
@rohitn6333
@rohitn6333 Жыл бұрын
understood sir
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi 9 ай бұрын
Great Video as Always..!
@Shivanai_h
@Shivanai_h Жыл бұрын
Understood 👏
@riteshkumargupta4001
@riteshkumargupta4001 Жыл бұрын
understood bhaiya
@dharanyuvi6951
@dharanyuvi6951 17 күн бұрын
Understood Striver thanks
@officialashish5224
@officialashish5224 Жыл бұрын
understood!
@tatipamularaviteja5245
@tatipamularaviteja5245 Жыл бұрын
understood❤
@suryakiran2970
@suryakiran2970 Жыл бұрын
Understood❤
@nilakshirekhawar2861
@nilakshirekhawar2861 13 күн бұрын
according to code: parent[ulp_v] = ulp_u; but at timestamp 05:30 we are attaching node 6 to node 2, shouldn't 6 gets attached to ultimate parent of 2 i.e. 1 instead ?
@priyan8004
@priyan8004 Жыл бұрын
Understood !
@phen8318
@phen8318 2 ай бұрын
Can we use priority queue here, instead of sorting the vector?
@shivanshpatel7352
@shivanshpatel7352 Жыл бұрын
Mast hai bhai
@sanchitdeepsingh9663
@sanchitdeepsingh9663 29 күн бұрын
thanks sir
@manojnavinjamuri5867
@manojnavinjamuri5867 Жыл бұрын
understood
@ujalavarshney480
@ujalavarshney480 Жыл бұрын
Understood
@kandariarjun
@kandariarjun 2 ай бұрын
Understood!!
@AryanMathur-gh6df
@AryanMathur-gh6df 9 ай бұрын
UNDERSTOOD
@shreyarawatvlogs6920
@shreyarawatvlogs6920 6 ай бұрын
cant we directly sort adj list??? Why do we have to make vector edges?
@_Deepak__Verma
@_Deepak__Verma 4 ай бұрын
how do you calculated time complexity it's typical to understand
@AmanGupta-ib5ss
@AmanGupta-ib5ss Жыл бұрын
understood :)
@chiragbirla5606
@chiragbirla5606 Жыл бұрын
The logic kind of is if you join the edge with the same ultimate parent it would cause a cycle which is not allowed
@priyanshkumar_iitd
@priyanshkumar_iitd Ай бұрын
Yeah!!
@dreamyme543
@dreamyme543 10 ай бұрын
Understood:)
@The_Shubham_Soni
@The_Shubham_Soni 10 ай бұрын
Understood.
@ce003abhimanyu9
@ce003abhimanyu9 5 ай бұрын
why not added both direction edges?
@vaibhavs2740
@vaibhavs2740 7 күн бұрын
I solved this by myself after learning DSU, can I say I'm also a co-inventor of Kruskal's algortihm.
@ugthesep5706
@ugthesep5706 2 күн бұрын
genius 😅
@durgeshjadhav01
@durgeshjadhav01 Ай бұрын
nice
@Purvilicious
@Purvilicious 10 ай бұрын
why do we need bidirectional AL in here? unidirectional also gives same results
@codewithasma8494
@codewithasma8494 Жыл бұрын
On GFG this approach is giving TLE can someone help me to understand
@codecrafts5263
@codecrafts5263 5 ай бұрын
but in code we were connecting ultimate parent of u with v, why are we connecting with u and v?
@prasadjambhale6670
@prasadjambhale6670 Жыл бұрын
So which method is efficient for finding mst krushkal's or prim's
@lucygaming9726
@lucygaming9726 7 ай бұрын
Both appears to have same TC
@technogaurav7980
@technogaurav7980 Ай бұрын
why is the *2 used in time complexity
@ashrafmohammad2784
@ashrafmohammad2784 Жыл бұрын
I have a question. How to write code of the program to calculate/print all spanning trees of a graph? If anyone can help me with the code I shall be obliged🙏🙏
@saurabhsagar3134
@saurabhsagar3134 Жыл бұрын
Edges print krna hai jo ki part hai mst ka
@shivanshchakrawarti5582
@shivanshchakrawarti5582 10 ай бұрын
Give more info Does the graph have all nodes connected to one another? If so then you would need to find the positions where two different edges with the same weight connect to the new node then you can create two minimum spanning trees here and if you again find this position then there will be 4 and so on
@sumanthreddy7670
@sumanthreddy7670 Ай бұрын
why will the disjoint set ignore the undirected edges in the adjacency list? why will only one edge be considered in disjoint set?
@harshith4549
@harshith4549 Ай бұрын
Next time you are going to union by size for that same edge, the two nodes are already in the same component which is why the first check of making sure if the given two nodes are in same component or not which tells "you are already in one part just go - no need to do anything"
@roshangeorge97
@roshangeorge97 8 ай бұрын
btw this video is not yet updated with Striver SDE Sheet, had to search up this manually!!
@googleit2490
@googleit2490 11 ай бұрын
Understood :) Sep'5, 2023 12:03 am Advice to self: I guess I will need to revise again after week and month; seems Tricky
@prisha1765
@prisha1765 Жыл бұрын
class Disjointset { vectorrank,parent; public: Disjointset(int n) { rank.resize(n+1,0); parent.resize(n+1); for(int i=1;i
@itsaryanb9316
@itsaryanb9316 Жыл бұрын
maybe initializing a priority queue of min heap to store the weights along with the node and the adjacent node would be better than to store them in a vector and later sort them?? correct me if I'm wrong?
@stephen9726
@stephen9726 Жыл бұрын
It's giving TLE when Min Heap is used. Maybe because of using top and pop while creating the disjoint set which takes O(logN) compared to O(1) when we use a Vector.
@shivamchoudhury9791
@shivamchoudhury9791 8 ай бұрын
Why twice the (Mx4xalpha)? Please let me know if I am wrong, but It should be (M+N) x4x alpha because we are making the union N-1 times.
@debangshudey5515
@debangshudey5515 4 ай бұрын
Firstly the number of times we are checking the ultimate parent is same as the number of edges so it is M*4*alpha. Second, both the findUPar and UnionBySize is executing simultaneously that's why 2 is getting mutltiplied. This simultaneous execution will be very less but for safety reasons we are multiplying 2 .
@softwarefoodiee
@softwarefoodiee Жыл бұрын
We can use min heap instead of sorting the vector.
@jagannathanav5108
@jagannathanav5108 Жыл бұрын
Same Time complexity , to form min Heap and sort but using min heap once again we have to perform logE times to extract minimum in sorting there's no need so sort is better TLDR; sorting E+ElogE and minheap ElogE + ElogE
@ayushvarun1425
@ayushvarun1425 Жыл бұрын
what is aplha???i have forgotten about it.....can anyone explain it??
@anshumaan1024
@anshumaan1024 Жыл бұрын
its value is nearly 1
@champion5946
@champion5946 Жыл бұрын
@codingalley6229
@codingalley6229 Жыл бұрын
🐐
@DeepakSingh-lr1og
@DeepakSingh-lr1og 3 ай бұрын
Can anyone tell me why 2 is connected to 1, it should be connected to 4, according to the disjoint set?
@harshith4549
@harshith4549 Ай бұрын
If 2 is connected to 4, It is not the minimum spanning tree and according to disjoint set, the ultimate parent of 4 is 1 and ultimate parent for 2 is 2 itself. 1 size(=2) is greater than 2 size(=1), which is why 2 is connected to 1.
@devans1244
@devans1244 10 ай бұрын
why are we not using visited array concept where if both vertex are visited we ignore the edge as it is making a loop
@saillaanil6948
@saillaanil6948 8 ай бұрын
good idea, have you tried solving using this way
@harshathammegowda1615
@harshathammegowda1615 8 ай бұрын
The next edge selection in Kruskal's is NOT always an incremental extension of the current MST path (like in Prim's it's 1 visited and 1 non-visited). The selection criteria here is just the next shortest edge weight and NO cycle). The selected edge need not even meet the MST path selected so far and hence result in 2 disconnected components. Similarly there could be many more disconnected components. Now when the edge which merges these components is selected, both the vertex are sort of visited... so how do you differentiate if it causes a cycle or its the 2 components merging?. Having just 2 arrays - visited and unvisited won't help. You'll require 1 array for unvisited, and as many separate visited arrays as there are different components. All this leads to just using a Disjoint set.
@arnabroy2995
@arnabroy2995 Жыл бұрын
@Yourclassmate
@Yourclassmate Жыл бұрын
Simple Approach:- class Solution{ static int spanningTree(int V, int E, int edges[][]){ Arrays.sort(edges, new Comparator() { @Override public int compare(final int[] entry1, final int[] entry2) { final int x = entry1[2]; final int y = entry2[2]; return Integer.compare(x, y); } }); DisjointSet ds = new DisjointSet(V); int mstwt = 0; for(int i = 0; i
@The_Shubham_Soni
@The_Shubham_Soni 10 ай бұрын
We have to write this whole DisjointSet class everytime for this type of questions?💀💀
@anshumaan1024
@anshumaan1024 Жыл бұрын
ye vector adj[] kya cheez hai ? vector adj[] toh adj. list hoti hai pta hai 🤔🤔
@lofireverbz-wy7go
@lofireverbz-wy7go 11 ай бұрын
2d vector hai jaise single vector mai sirf tum (node) store krte ho and double vector mai (node,weight)
@pratyakshhhhhhhhhhhhhhhhhhhhh
@pratyakshhhhhhhhhhhhhhhhhhhhh 7 ай бұрын
🎉
@shreedevimg
@shreedevimg Ай бұрын
when he said for java people i am like😎
@atharm.7319
@atharm.7319 Жыл бұрын
Python : ``` class UnionFind: def __init__(self,n): self.parent = [i for i in range(n)] self.size = [1 for i in range(n)] def union(self,u,v): parent_u = self.find(u) parent_v = self.find(v) if parent_u == parent_v: return True if self.size[parent_u] < self.size[parent_v]: self.parent[parent_u] = parent_v self.size[parent_v] += self.size[parent_u] else: self.parent[parent_v] = parent_u self.size[parent_u] += self.size[parent_v] return False def find(self,u): if u == self.parent[u]: return u self.parent[u] = self.find(self.parent[u]) return self.parent[u] class Solution: #Function to find sum of weights of edges of the Minimum Spanning Tree. def spanningTree(self, V, adj): edges = [] for i in range(V): for u , wt in adj[i]: edges.append([i,u,wt]) edges.sort(key = lambda x : x[2]) ds = UnionFind(V) res = 0 for u , v , wt in edges: if ds.find(u) != ds.find(v): res += wt ds.union(u,v) return res ```
@AshmitIITH
@AshmitIITH Ай бұрын
Thanks bro
@techinfolbf1225
@techinfolbf1225 Жыл бұрын
No one can match striver energy and research for every video .........
@vivekpawar311
@vivekpawar311 Жыл бұрын
US
@ProudSanataniHindu1008
@ProudSanataniHindu1008 Жыл бұрын
Can you please explain Java code also along with C++
@rajstriver5875
@rajstriver5875 Жыл бұрын
How tough is it to understand loops, if you are reading graphs, you should have that thing to read code in any language, cpp and java hardly have much difference. Learn to understand logic, codes can follow. Else you will be struggling in your job with so much of spoon feeding. The code is there, just read it mate. And understand the cpp explanation. It runs parallely
@Shivanai_h
@Shivanai_h Жыл бұрын
Exactly 💯 I am also a java person but its understandable.
@amanagrawal1951
@amanagrawal1951 Жыл бұрын
@@rajstriver5875 then please explain me why collectons.sort and comparable class both are used for ArrayList edges........if you know then please
@amanagrawal1951
@amanagrawal1951 Жыл бұрын
@@Shivanai_h why comparator is used in class Edge and later why we used collections.sort.....I am confused
@prathambhushan4859
@prathambhushan4859 Ай бұрын
@@rajstriver5875 bhai fir edge class smjha
@AbhijeetSingh-rx9ef
@AbhijeetSingh-rx9ef Жыл бұрын
Why can't we use just the parent array to find out the ultimate parents of u and v?
@phoenix_1_3
@phoenix_1_3 Жыл бұрын
That's what we are doing in findParent(). Whenever we insert a node to a set of nodes, the parent of the inserted node will change. So everytime we needa use findParent() func
@usnikdaripa
@usnikdaripa 10 ай бұрын
babbar bhaiya ne graph k naam pe kaat diya hain
@kushagramishra3026
@kushagramishra3026 Жыл бұрын
"Understood"
@snipper6683
@snipper6683 2 ай бұрын
Koi indore se hai kya bhai
@ankitraj2283
@ankitraj2283 Жыл бұрын
Here is java code of gfg practise link class Solution { static class DisjointSet { List rank = new ArrayList(); List parent = new ArrayList(); public DisjointSet(int n) { for (int i = 0; i
@roshangeorge97
@roshangeorge97 8 ай бұрын
Thanks:)
@modiji8706
@modiji8706 8 ай бұрын
thnxx
@thaman701
@thaman701 29 күн бұрын
bhai yr ye comparator or comparable smjh ni aara hain koi video bata de yr kaha se smjhu usko pliz
@Mohit_Q
@Mohit_Q 6 ай бұрын
21jan 2024 7:10
@prathambhushan4859
@prathambhushan4859 Ай бұрын
Have to write disjoint code💀💀
@KratosProton
@KratosProton Жыл бұрын
a
@devsrivastava2300
@devsrivastava2300 Жыл бұрын
code for someone who does not find declaring class , intuitive in exams int findpar(int &a,vector &parent) { if(a==parent[a]) { return a; } return parent[a] = findpar(parent[a],parent); } int spanningTree(int V, vector adj[]) { vector parent(V); for(int i=0;i
@prathambhushan4859
@prathambhushan4859 Ай бұрын
any java peeps, pls help me I am stuck at the code
@studybits1604
@studybits1604 10 ай бұрын
us
@AkashKumar-eo8ku
@AkashKumar-eo8ku 2 ай бұрын
java kruskal algorithm, creating edges list from adjacency list class Solution{ static class DisJointSetSize { // UNION BY SIZE; MORE INTUITIVE; KRUSKAL ALGORITHM SUBMITTED AND TESTED for gfg List parent = new ArrayList(); List size = new ArrayList(); public DisJointSetSize(int n) { for (int i = 0; i a[2] - b[2]); DisJointSetSize dsu = new DisJointSetSize(V); int sum = 0; for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; int weight = edge[2]; if (dsu.findUltimateParent(u) != dsu.findUltimateParent(v)) { dsu.unionBySize(u, v); sum += weight; } } return sum; } }
@thaman701
@thaman701 29 күн бұрын
bhai yr ye lambda expression smjh hi ni aari h kaha se clear kru ise bata do yr
@KratosProton
@KratosProton Жыл бұрын
t
@nkvs1248
@nkvs1248 Жыл бұрын
U.S.
@KratosProton
@KratosProton Жыл бұрын
e
@p38_amankuldeep75
@p38_amankuldeep75 Жыл бұрын
understood💙🤍💙
@river.
@river. 9 ай бұрын
i am python people. please help us python people too
@shubhamkumar-hx1fb
@shubhamkumar-hx1fb 4 ай бұрын
then..Do u want him to teach python?
@river.
@river. 4 ай бұрын
@@shubhamkumar-hx1fb actually no. I am now a consultant analyst people. Fate guides my destination 🤘
@rahulnagwanshi2348
@rahulnagwanshi2348 Жыл бұрын
2:41 "Everyone will be a single guy" so basically he meant "Sabka Katega🔪"
@kartikdalai7998
@kartikdalai7998 11 ай бұрын
public class KrushkalDriver { public static void main(String[] args) { findMSTCost(createWeightedGraph()); } public static void findMSTCost(ArrayList[] graph){ ArrayList list = new ArrayList(); for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph[i].size(); j++) { list.add(graph[i].get(j)); } } Collections.sort(list,(o1, o2) -> o1.weight- o2.weight); DisjointSet d = new DisjointSet(graph.length); int cost =0; for (Edge e:list ) { if(d.addBySize(e.src,e.dst)){ cost= cost+e.weight; } } System.out.println(cost); } public static ArrayList[] createWeightedGraph(){ int V = 4; ArrayList[] graph = new ArrayList[V]; for (int i = 0; i < V; i++) { graph[i] = new ArrayList(); } graph[0].add(new Edge(0,1,10)); graph[0].add(new Edge(0,2,15)); graph[0].add(new Edge(0,3,30)); graph[1].add(new Edge(1,0,10)); graph[1].add(new Edge(1,3,40)); graph[2].add(new Edge(2,0,15)); graph[2].add(new Edge(2,3,50)); graph[3].add(new Edge(3,1,40)); graph[3].add(new Edge(3,0,30)); graph[3].add(new Edge(3,2,50)); return graph; } } class Edge{ int src; int dst; int weight; public Edge(int src, int dst, int weight) { this.src = src; this.dst = dst; this.weight = weight; } } class DisjointSet{ ArrayList size = new ArrayList(); ArrayList parent = new ArrayList(); public DisjointSet(int n) { for (int i = 0; i sizeV){ parent.set(ulPv,ulPu); size.set(ulPu,sizeU+sizeV); }else { parent.set(ulPu,ulPv); size.set(ulPv,sizeU+sizeV); } return true; } }
G-48. Number of Provinces - Disjoint Set
8:03
take U forward
Рет қаралды 65 М.
G-46. Disjoint Set | Union by Rank | Union by Size | Path Compression
42:15
A little girl was shy at her first ballet lesson #shorts
00:35
Fabiosa Animated
Рет қаралды 16 МЛН
G-45. Prim's Algorithm - Minimum Spanning Tree - C++ and Java
19:10
take U forward
Рет қаралды 217 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 633 М.
Understand Common Time Complexities with Real Code and Tests
22:54
3.5 Prims and Kruskals Algorithms - Greedy Method
20:12
Abdul Bari
Рет қаралды 2,7 МЛН
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 807 М.
G-50. Accounts Merge - DSU
22:01
take U forward
Рет қаралды 84 М.
Solve Any Pattern Question With This Trick!
57:20
Kunal Kushwaha
Рет қаралды 2,3 МЛН
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 289 М.
Kadane's Algorithm | Maximum Subarray Sum | Finding and Printing
20:09
take U forward
Рет қаралды 363 М.