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

  Рет қаралды 152,628

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
---------------------------------------------------------------------------------------------------------------------------

Пікірлер: 187
@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 3 ай бұрын
I am not getting what the M and N stands for, when you are calculating time complexities.
@KiranKumar-sb3ti
@KiranKumar-sb3ti 28 күн бұрын
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!
@suryasingh2563
@suryasingh2563 Жыл бұрын
Fully understood bhaiya...
@prasannasippa5962
@prasannasippa5962 Жыл бұрын
understood striver.... Thank you so much
@stith_pragya
@stith_pragya 7 ай бұрын
Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@mohammadahsan7873
@mohammadahsan7873 7 ай бұрын
Superb Explanations... ❤👏
@udaytewary3809
@udaytewary3809 Жыл бұрын
Understood bhaiya 🙏❤️
@amantripathi4100
@amantripathi4100 Жыл бұрын
Bhai indeed the best teacher
@ajaybabupatel1665
@ajaybabupatel1665 Жыл бұрын
understood, thanks raj
@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 9 ай бұрын
@@vishnubanjara5209 i still didnt get it
@abhishekkuntare4640
@abhishekkuntare4640 Жыл бұрын
Understood Raj bhaiyaa ❤❤
@suryasingh2563
@suryasingh2563 Жыл бұрын
Understood Bhaiya❣
@parshchoradia9909
@parshchoradia9909 Жыл бұрын
Understood Sir!
@UECAshutoshKumar
@UECAshutoshKumar 7 ай бұрын
Thank you sir 🙏
@user-fs8km9qc8f
@user-fs8km9qc8f 21 күн бұрын
very nice explanation
@anshulagarwal6682
@anshulagarwal6682 Жыл бұрын
Please also make video on dp on trees, heavy light decomposition.
@UjjwalPratapSingh-hh6wu
@UjjwalPratapSingh-hh6wu Жыл бұрын
Understood 👍🏻
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi 9 ай бұрын
Great Video as Always..!
@mugambo5505
@mugambo5505 Жыл бұрын
understood thanks sir ❣❣❣❣
@Shivanai_h
@Shivanai_h Жыл бұрын
Understood 👏
@herculean6748
@herculean6748 Жыл бұрын
Thanks🙌
@riteshkumargupta4001
@riteshkumargupta4001 Жыл бұрын
understood bhaiya
@rohitn6333
@rohitn6333 Жыл бұрын
understood sir
@officialashish5224
@officialashish5224 Жыл бұрын
understood!
@dharanyuvi6951
@dharanyuvi6951 5 күн бұрын
Understood Striver thanks
@tatipamularaviteja5245
@tatipamularaviteja5245 Жыл бұрын
understood❤
@suryakiran2970
@suryakiran2970 Жыл бұрын
Understood❤
@priyan8004
@priyan8004 11 ай бұрын
Understood !
@AryanMathur-gh6df
@AryanMathur-gh6df 9 ай бұрын
UNDERSTOOD
@AmanGupta-ib5ss
@AmanGupta-ib5ss Жыл бұрын
understood :)
@amanxsharma
@amanxsharma Жыл бұрын
understood
@sanchitdeepsingh9663
@sanchitdeepsingh9663 17 күн бұрын
thanks sir
@dreamyme543
@dreamyme543 10 ай бұрын
Understood:)
@shivanshpatel7352
@shivanshpatel7352 Жыл бұрын
Mast hai bhai
@ujalavarshney480
@ujalavarshney480 Жыл бұрын
Understood
@kandariarjun
@kandariarjun 2 ай бұрын
Understood!!
@The_Shubham_Soni
@The_Shubham_Soni 10 ай бұрын
Understood.
@phen8318
@phen8318 Ай бұрын
Can we use priority queue here, instead of sorting the vector?
@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
@priyanshkumariitd
@priyanshkumariitd Ай бұрын
Yeah!!
@durgeshjadhav01
@durgeshjadhav01 22 күн бұрын
nice
@ce003abhimanyu9
@ce003abhimanyu9 4 ай бұрын
why not added both direction edges?
@_Deepak__Verma
@_Deepak__Verma 4 ай бұрын
how do you calculated time complexity it's typical to understand
@shreyarawatvlogs6920
@shreyarawatvlogs6920 6 ай бұрын
cant we directly sort adj list??? Why do we have to make vector edges?
@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
@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
@nilakshirekhawar2861
@nilakshirekhawar2861 Күн бұрын
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 ?
@roshangeorge97
@roshangeorge97 8 ай бұрын
btw this video is not yet updated with Striver SDE Sheet, had to search up this manually!!
@technogaurav7980
@technogaurav7980 Ай бұрын
why is the *2 used in time complexity
@prasadjambhale6670
@prasadjambhale6670 Жыл бұрын
So which method is efficient for finding mst krushkal's or prim's
@lucygaming9726
@lucygaming9726 6 ай бұрын
Both appears to have same TC
@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
@champion5946
@champion5946 Жыл бұрын
@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 28 күн бұрын
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"
@ayushvarun1425
@ayushvarun1425 Жыл бұрын
what is aplha???i have forgotten about it.....can anyone explain it??
@anshumaan1024
@anshumaan1024 11 ай бұрын
its value is nearly 1
@codingalley6229
@codingalley6229 Жыл бұрын
🐐
@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 3 ай бұрын
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 .
@devans1244
@devans1244 9 ай бұрын
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 7 ай бұрын
good idea, have you tried solving using this way
@harshathammegowda1615
@harshathammegowda1615 7 ай бұрын
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.
@googleit2490
@googleit2490 10 ай бұрын
Understood :) Sep'5, 2023 12:03 am Advice to self: I guess I will need to revise again after week and month; seems Tricky
@codecrafts5263
@codecrafts5263 5 ай бұрын
but in code we were connecting ultimate parent of u with v, why are we connecting with u and v?
@arnabroy2995
@arnabroy2995 Жыл бұрын
@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 28 күн бұрын
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.
@pratyakshhhhhhhhhhhhhhhhhhhhh
@pratyakshhhhhhhhhhhhhhhhhhhhh 7 ай бұрын
🎉
@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?💀💀
@shreedevimg
@shreedevimg 19 күн бұрын
when he said for java people i am like😎
@anshumaan1024
@anshumaan1024 11 ай бұрын
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)
@techinfolbf1225
@techinfolbf1225 Жыл бұрын
No one can match striver energy and research for every video .........
@prisha1765
@prisha1765 Жыл бұрын
class Disjointset { vectorrank,parent; public: Disjointset(int n) { rank.resize(n+1,0); parent.resize(n+1); for(int i=1;i
@vivekpawar311
@vivekpawar311 Жыл бұрын
US
@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
@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
@snipper6683
@snipper6683 Ай бұрын
Koi indore se hai kya bhai
@kushagramishra3026
@kushagramishra3026 Жыл бұрын
"Understood"
@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 26 күн бұрын
Thanks bro
@usnikdaripa
@usnikdaripa 10 ай бұрын
babbar bhaiya ne graph k naam pe kaat diya hain
@Mohit_Q
@Mohit_Q 6 ай бұрын
21jan 2024 7:10
@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 17 күн бұрын
bhai yr ye comparator or comparable smjh ni aara hain koi video bata de yr kaha se smjhu usko pliz
@prathambhushan4859
@prathambhushan4859 Ай бұрын
any java peeps, pls help me I am stuck at the code
@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
@KratosProton
@KratosProton Жыл бұрын
a
@prathambhushan4859
@prathambhushan4859 Ай бұрын
Have to write disjoint code💀💀
@studybits1604
@studybits1604 9 ай бұрын
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 17 күн бұрын
bhai yr ye lambda expression smjh hi ni aari h kaha se clear kru ise bata do yr
@KratosProton
@KratosProton Жыл бұрын
t
@KratosProton
@KratosProton Жыл бұрын
e
@p38_amankuldeep75
@p38_amankuldeep75 Жыл бұрын
understood💙🤍💙
@nkvs1248
@nkvs1248 Жыл бұрын
U.S.
@river.
@river. 8 ай бұрын
i am python people. please help us python people too
@shubhamkumar-hx1fb
@shubhamkumar-hx1fb 3 ай бұрын
then..Do u want him to teach python?
@river.
@river. 3 ай бұрын
@@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; } }
@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.
@shaikabdulsalambatcha4322
@shaikabdulsalambatcha4322 Жыл бұрын
Optimal Java Code: class DisjointSetUnion { ArrayList parent=new ArrayList(); ArrayList rank=new ArrayList(); public DisjointSetUnion(int n){ for(int i=0;i rank.get(ulv)){ parent.set(ulv,ulu); } else{ parent.set(ulv,ulu); int ranku=rank.get(ulu); rank.set(ulu, ranku+1); } } } class Solution{ static int spanningTree(int V, int E, int edges[][]){ // Code Here. Arrays.sort(edges,(x,y)->x[2]-y[2]); DisjointSetUnion ds=new DisjointSetUnion(V); int netwt=0; for(int[] num: edges){ int wt=num[2]; int u=num[0]; int v=num[1]; if(ds.findpar(u) != ds.findpar(v)){ netwt+=wt; ds.union(u,v); } } return netwt; } }
@-VLaharika
@-VLaharika Жыл бұрын
Understood 👍
G-48. Number of Provinces - Disjoint Set
8:03
take U forward
Рет қаралды 63 М.
G-46. Disjoint Set | Union by Rank | Union by Size | Path Compression
42:15
Now THIS is entertainment! 🤣
00:59
America's Got Talent
Рет қаралды 39 МЛН
Little girl's dream of a giant teddy bear is about to come true #shorts
00:32
Looks realistic #tiktok
00:22
Анастасия Тарасова
Рет қаралды 105 МЛН
G-45. Prim's Algorithm - Minimum Spanning Tree - C++ and Java
19:10
take U forward
Рет қаралды 210 М.
30 Days Javascript LeetCode Challenge | Day-1 | Vishwa Mohan
21:55
Vishwa Mohan
Рет қаралды 3,4 М.
VICKY KAUSHAL REACTS TO VICKY KAUSHAL MEMES ft. VICKY KAUSHAL
26:42
Tanmay Bhat
Рет қаралды 6 МЛН
Understanding B-Trees: The Data Structure Behind Modern Databases
12:39
The Last Algorithms Course You'll Need by ThePrimeagen | Preview
16:44
Frontend Masters
Рет қаралды 312 М.
3.5 Prims and Kruskals Algorithms - Greedy Method
20:12
Abdul Bari
Рет қаралды 2,7 МЛН
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 625 М.
Now THIS is entertainment! 🤣
00:59
America's Got Talent
Рет қаралды 39 МЛН