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

Поділитися
Вставка
  • Опубліковано 21 жов 2022
  • 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
    ---------------------------------------------------------------------------------------------------------------------------

КОМЕНТАРІ • 179

  • @takeUforward
    @takeUforward  Рік тому +42

    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 8 днів тому

      understood

  • @coding8000
    @coding8000 Рік тому +64

    you will be remembered in all three tenses i.e past, current, future., keep going bro, my power to you.

  • @SumitKeshariMCS
    @SumitKeshariMCS Рік тому +14

    Understood each and every second of the video. Thanks Striver.

  • @kshitijmishra2716
    @kshitijmishra2716 Рік тому +43

    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 Рік тому +4

      bhai kehna kya chhata hai ?

    • @vishnubanjara5209
      @vishnubanjara5209 Рік тому +7

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

  • @raghavagrawal9240
    @raghavagrawal9240 Рік тому +1

    Was waiting for the series to continue! Thanks

  • @cinime
    @cinime Рік тому +3

    Understood! Super wonderful explanation as always, thank you!!

  • @averylazyandweirdhuman
    @averylazyandweirdhuman 23 дні тому

    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 Рік тому +1

    Understood!
    Super wonderful explanation❤

  • @sahillakhani1962
    @sahillakhani1962 10 місяців тому

    well explained sir. Understood clearly!

  • @rishabhgupta9846
    @rishabhgupta9846 Рік тому +2

    understood,great explanation

  • @mohammadahsan7873
    @mohammadahsan7873 7 місяців тому

    Superb Explanations... ❤👏

  • @stith_pragya
    @stith_pragya 6 місяців тому +2

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @prasannasippa5962
    @prasannasippa5962 Рік тому

    understood striver.... Thank you so much

  • @suryasingh2563
    @suryasingh2563 Рік тому

    Fully understood bhaiya...

  • @amantripathi4100
    @amantripathi4100 Рік тому +1

    Bhai indeed the best teacher

  • @udaytewary3809
    @udaytewary3809 Рік тому +1

    Understood bhaiya 🙏❤️

  • @anshulagarwal6682
    @anshulagarwal6682 Рік тому +3

    Please also make video on dp on trees, heavy light decomposition.

  • @abhishekkuntare4640
    @abhishekkuntare4640 Рік тому

    Understood Raj bhaiyaa ❤❤

  • @ajaybabupatel1665
    @ajaybabupatel1665 11 місяців тому +1

    understood, thanks raj

  • @suryasingh2563
    @suryasingh2563 Рік тому

    Understood Bhaiya❣

  • @user-fs8km9qc8f
    @user-fs8km9qc8f 23 години тому

    very nice explanation

  • @parshchoradia9909
    @parshchoradia9909 Рік тому

    Understood Sir!

  • @UECAshutoshKumar
    @UECAshutoshKumar 6 місяців тому +1

    Thank you sir 🙏

  • @phen8318
    @phen8318 Місяць тому +1

    Can we use priority queue here, instead of sorting the vector?

  • @chiragbirla5606
    @chiragbirla5606 Рік тому +8

    The logic kind of is if you join the edge with the same ultimate parent it would cause a cycle which is not allowed

  • @UjjwalPratapSingh-hh6wu
    @UjjwalPratapSingh-hh6wu Рік тому

    Understood 👍🏻

  • @mugambo5505
    @mugambo5505 Рік тому

    understood thanks sir ❣❣❣❣

  • @riteshkumargupta4001
    @riteshkumargupta4001 Рік тому

    understood bhaiya

  • @Shivanai_h
    @Shivanai_h Рік тому

    Understood 👏

  • @rohitn6333
    @rohitn6333 Рік тому +1

    understood sir

  • @shreyarawatvlogs6920
    @shreyarawatvlogs6920 5 місяців тому

    cant we directly sort adj list??? Why do we have to make vector edges?

  • @herculean6748
    @herculean6748 Рік тому

    Thanks🙌

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi 8 місяців тому

    Great Video as Always..!

  • @officialashish5224
    @officialashish5224 Рік тому

    understood!

  • @_Deepak__Verma
    @_Deepak__Verma 3 місяці тому

    how do you calculated time complexity it's typical to understand

  • @suryakiran2970
    @suryakiran2970 Рік тому

    Understood❤

  • @kandariarjun
    @kandariarjun Місяць тому

    Understood!!

  • @tatipamularaviteja5245
    @tatipamularaviteja5245 Рік тому

    understood❤

  • @priyan8004
    @priyan8004 10 місяців тому

    Understood !

  • @AryanMathur-gh6df
    @AryanMathur-gh6df 8 місяців тому

    UNDERSTOOD

  • @ce003abhimanyu9
    @ce003abhimanyu9 4 місяці тому +1

    why not added both direction edges?

  • @Purvilicious
    @Purvilicious 9 місяців тому

    why do we need bidirectional AL in here? unidirectional also gives same results

  • @rishabhthakur5414
    @rishabhthakur5414 Місяць тому

    understood

  • @itsaryanb9316
    @itsaryanb9316 Рік тому +5

    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 Рік тому +2

      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.

  • @roshangeorge97
    @roshangeorge97 7 місяців тому

    btw this video is not yet updated with Striver SDE Sheet, had to search up this manually!!

  • @ujalavarshney480
    @ujalavarshney480 Рік тому +1

    Understood

  • @dreamyme543
    @dreamyme543 9 місяців тому

    Understood:)

  • @AmanGupta-ib5ss
    @AmanGupta-ib5ss Рік тому

    understood :)

  • @shivanshpatel7352
    @shivanshpatel7352 Рік тому

    Mast hai bhai

  • @prasadjambhale6670
    @prasadjambhale6670 Рік тому +2

    So which method is efficient for finding mst krushkal's or prim's

  • @The_Shubham_Soni
    @The_Shubham_Soni 9 місяців тому

    Understood.

  • @ashrafmohammad2784
    @ashrafmohammad2784 Рік тому +4

    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 9 місяців тому

      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

  • @codewithasma8494
    @codewithasma8494 Рік тому

    On GFG this approach is giving TLE can someone help me to understand

  • @shivamchoudhury9791
    @shivamchoudhury9791 7 місяців тому

    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 .

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

  • @durgeshjadhav01
    @durgeshjadhav01 2 дні тому

    nice

  • @technogaurav7980
    @technogaurav7980 27 днів тому

    why is the *2 used in time complexity

  • @sumanthreddy7670
    @sumanthreddy7670 11 днів тому

    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 8 днів тому

      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"

  • @codecrafts5263
    @codecrafts5263 4 місяці тому

    but in code we were connecting ultimate parent of u with v, why are we connecting with u and v?

  • @prisha1765
    @prisha1765 Рік тому +4

    class Disjointset
    {
    vectorrank,parent;
    public:
    Disjointset(int n)
    {
    rank.resize(n+1,0);
    parent.resize(n+1);
    for(int i=1;i

  • @devans1244
    @devans1244 9 місяців тому +2

    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 6 місяців тому +2

      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

  • @ayushvarun1425
    @ayushvarun1425 11 місяців тому +1

    what is aplha???i have forgotten about it.....can anyone explain it??

  • @codingalley6229
    @codingalley6229 Рік тому

    🐐

  • @DeepakSingh-lr1og
    @DeepakSingh-lr1og 2 місяці тому

    Can anyone tell me why 2 is connected to 1, it should be connected to 4, according to the disjoint set?

    • @harshith4549
      @harshith4549 8 днів тому

      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.

  • @arnabroy2995
    @arnabroy2995 Рік тому

  • @Yourclassmate
    @Yourclassmate Рік тому +1

    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

  • @champion5946
    @champion5946 Рік тому

  • @pratyakshhhhhhhhhhhhhhhhhhhhh
    @pratyakshhhhhhhhhhhhhhhhhhhhh 6 місяців тому

    🎉

  • @anshumaan1024
    @anshumaan1024 11 місяців тому +1

    ye vector adj[] kya cheez hai ?
    vector adj[] toh adj. list hoti hai pta hai 🤔🤔

    • @lofireverbz-wy7go
      @lofireverbz-wy7go 10 місяців тому

      2d vector hai jaise single vector mai sirf tum (node) store krte ho and double vector mai (node,weight)

  • @Bigbull245
    @Bigbull245 Рік тому

    Can you please explain Java code also along with C++

    • @rajstriver5875
      @rajstriver5875 Рік тому +10

      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 Рік тому +4

      Exactly 💯
      I am also a java person but its understandable.

    • @amanagrawal1951
      @amanagrawal1951 Рік тому +2

      @@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 15 днів тому

      @@rajstriver5875 bhai fir edge class smjha

  • @The_Shubham_Soni
    @The_Shubham_Soni 9 місяців тому

    We have to write this whole DisjointSet class everytime for this type of questions?💀💀

  • @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 11 місяців тому

      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

  • @techinfolbf1225
    @techinfolbf1225 Рік тому +1

    No one can match striver energy and research for every video .........

  • @atharm.7319
    @atharm.7319 Рік тому +8

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

  • @vivekpawar311
    @vivekpawar311 Рік тому

    US

  • @ankitraj2283
    @ankitraj2283 Рік тому +4

    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

  • @snipper6683
    @snipper6683 Місяць тому

    Koi indore se hai kya bhai

  • @prathambhushan4859
    @prathambhushan4859 15 днів тому

    any java peeps, pls help me I am stuck at the code

  • @kushagramishra3026
    @kushagramishra3026 Рік тому

    "Understood"

  • @devsrivastava2300
    @devsrivastava2300 11 місяців тому

    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

  • @usnikdaripa
    @usnikdaripa 9 місяців тому

    babbar bhaiya ne graph k naam pe kaat diya hain

  • @ky747r0
    @ky747r0 Рік тому

    a

  • @AkashKumar-eo8ku
    @AkashKumar-eo8ku Місяць тому

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

  • @Mohit_Q
    @Mohit_Q 5 місяців тому

    21jan 2024 7:10

  • @studybits1604
    @studybits1604 9 місяців тому

    us

  • @ky747r0
    @ky747r0 Рік тому

    e

  • @ky747r0
    @ky747r0 Рік тому

    t

  • @p38_amankuldeep75
    @p38_amankuldeep75 Рік тому

    understood💙🤍💙

  • @prathambhushan4859
    @prathambhushan4859 15 днів тому

    Have to write disjoint code💀💀

  • @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 🤘

  • @nkvs1248
    @nkvs1248 Рік тому

    U.S.

  • @rahulnagwanshi2348
    @rahulnagwanshi2348 Рік тому

    2:41 "Everyone will be a single guy" so basically he meant "Sabka Katega🔪"

  • @kartikdalai7998
    @kartikdalai7998 10 місяців тому

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

  • @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 👍

  • @RituSingh-ne1mk
    @RituSingh-ne1mk 5 місяців тому

    Understood!

  • @user-of1eg7oy4u
    @user-of1eg7oy4u Місяць тому

    understood

  • @jinhuang7258
    @jinhuang7258 11 місяців тому

    Understood.

  • @LearnerForever123
    @LearnerForever123 9 місяців тому +1

    Understood