G-48. Number of Provinces - Disjoint Set

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 ต.ค. 2024

ความคิดเห็น • 105

  • @takeUforward
    @takeUforward  2 ปีที่แล้ว +15

    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

  • @devanshverma8050
    @devanshverma8050 ปีที่แล้ว +29

    i would advice not to use parent array for finding parent cuz in some cases it doesn't have correct parent values being updated (for eg in accounts merge question), also findpar function will always give correct results without any extra complexity cuz if the parent of particular node is already updated it will always fall in base case resulting in O(1) operation.

  • @BharatiSubramanian99217
    @BharatiSubramanian99217 ปีที่แล้ว +23

    There's also another way to do this. We can keep the count of components initially as n within the DSU class (as a member variable). That is each vertex is a component by itself. Every time we do a union between u and v, we can reduce the number of components by 1.
    Finally we can simply return this value.

    • @vishious14
      @vishious14 11 หลายเดือนก่อน

      I had the very same thing in my mind

  • @successsavataar.ai786
    @successsavataar.ai786 ปีที่แล้ว +7

    In this problem if we have 1 based indexing then why we are using for loop from 0 to n-1 , because for 1 based indexing ideally we should use for loop from 1 to n, and also the code of for loop from 0 to n-1 is working fine ... How??
    I was initially stucked but after looking and analysing the code I understood : Here is how ?
    in the union by size function we are actually making union for zero based indexing of the array
    so here are two ways =>
    1. ds.unionBySize(i,j); and run for loop from 0 to n-1 || zero based indexing
    2. ds.unionBySize(i+1,j+1); and run for loop from 1 to n || one based indexing
    I hope this will help someone || Happy coding 😊😊

  • @psurya3053
    @psurya3053 ปีที่แล้ว +3

    thank you, sir, I am self-preparing for my placements, your lectures are useful for most of us. Great teaching skills. i have watched entire graph series, and dp series.

  • @mugambo5505
    @mugambo5505 ปีที่แล้ว

    dsa driver striver i first solved this question myself then saw explanation. it's because of you now i am confident to do questions.

  • @sauravchandra10
    @sauravchandra10 ปีที่แล้ว

    Thanks to you I was able to solve this on my own without watching the explanation. As always, understood clearly!

  • @free.channel715
    @free.channel715 4 หลายเดือนก่อน

    we can also use a variable num = V and every time we do a union(u,v)we can do n - - ; int he union function only that way we don't have to run it extra loop to check for the count .

  • @potassium_cyanide_boy8515
    @potassium_cyanide_boy8515 ปีที่แล้ว +1

    i think rather than making parent array object as public, we can create one getter method that will just return us element at particulat index like this:
    int getParentEleme(int idx) const{
    if(idx < 0 || idx > n){
    throw std::invalid_argument( "illegal index value" );
    }
    return parent[idx];
    }
    Or overload [] operator for DisjointSet class

  • @viditgupta7088
    @viditgupta7088 2 ปีที่แล้ว +14

    hey striver great series.. thanks for the amazing content... Just one request meanwhile can you also share some of the codeforces questions based on graphs based on what we've learnt till now? It'll be really helpful

    • @takeUforward
      @takeUforward  2 ปีที่แล้ว +11

      You can check the CP sheet on the tuf site for the same, thanks

  • @spandanbhattacharya5030
    @spandanbhattacharya5030 ปีที่แล้ว +1

    Thank You for the amazing explanation Striver bhaiya!
    I judt had an observation that in the final loop where we are counting the number of par[i]=i, there if the count comes out to be 3, it doesn't mean that if we output the parent array in the end, it would not have only 3 distinct elements.
    It may have more, as the path compression updates only the ultimate parent. So, those who put the parent array into a set and outputted its size, they will get a wrong answer in some cases.
    Therefore, the condition which checks whether someone is an ultimate parent is if par[i]=i, otherwise it may cause errors in implementation (not logical error).

    • @tusharmittal3959
      @tusharmittal3959 4 หลายเดือนก่อน

      Hi I actually set and got the wrong answer. I did not understood it why it happened can u help me explain?

    • @spandanbhattacharya5030
      @spandanbhattacharya5030 4 หลายเดือนก่อน +1

      @@tusharmittal3959 Logically, the set contains all the super parents, so if we output the size of the set, it should give the number of disjoint sets.
      That would be true in this case too, if after path compression we updated the parents of each node after each compression. But we don't do that to save time.
      Thus, let's say 1 is the parent of 2 and 3, so number of parents currently =1.
      But now let's say 4 comes and 4 becomes the parent of 1, so logically, the parent of 1,2,3,4, all are 4. But, since we only update the case for 1. 2,3 still have 1 as their parent in the parent set.
      So, now if we count in the set, we will find 4,1 as 2 parents.
      Thus to avoid that, we use the rule par[i] = i, then only it's a super parent rule to determine number of parents.

    • @parthivsinhvaghela6100
      @parthivsinhvaghela6100 หลายเดือนก่อน

      @@spandanbhattacharya5030 but if 4 comes then size of 4 will be less than size of 1 so 4 is not going to be the parent of 1 since we always append small portion into big...

  • @stith_pragya
    @stith_pragya 10 หลายเดือนก่อน +1

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

  • @vishious14
    @vishious14 11 หลายเดือนก่อน

    Using a size array is not necessary because we dont really care about the size. We just want to see if their parents are same, if their parents are not then make one of them the parent of another. This is a little space optimization one could make.

  • @AbcdEfgh-dm2pg
    @AbcdEfgh-dm2pg ปีที่แล้ว

    When you are converting adjacency matrix to list, it should be adjLs[i+1].push_back(j+1) as the nodes are 1 based indexed so, doing adjLs[i].push_back[j] for row 0 say for example would mean there is edge between any node 'x' and node 0 which is false as node 0 doesn't exist

  • @cinime
    @cinime 2 ปีที่แล้ว

    Understood! So fantastic explanation as always, thank you!!

  • @MURTHATIMAHIBABU
    @MURTHATIMAHIBABU ปีที่แล้ว

    Hi striver really ur content is super, in similar way could u do for tress topic like binary lifting..etc

  • @oqant0424
    @oqant0424 ปีที่แล้ว

    Understood!
    So fantastic explanation

  • @anshulgoel1940
    @anshulgoel1940 9 หลายเดือนก่อน

    Or decrease the count by 1 on successful union instead of iterating over the parent array in the last

  • @RohitKumar-dy2gc
    @RohitKumar-dy2gc ปีที่แล้ว

    understood beautifully

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 ปีที่แล้ว

    Understood and thank alot for this amazing content

  • @rushidesai2836
    @rushidesai2836 9 หลายเดือนก่อน

    Thanks Striver!

  • @ast9831
    @ast9831 ปีที่แล้ว +1

    but the dfs approach was just O(V+E) , dsu is O(V^2)

  • @sapna2019
    @sapna2019 2 ปีที่แล้ว

    Understood thanku for creating such a good content

  • @joshuamanivinod9873
    @joshuamanivinod9873 3 หลายเดือนก่อน

    Thank you soo much!
    you are the best🔥

  • @TarunKumarSaraswat
    @TarunKumarSaraswat 9 วันที่ผ่านมา

    thanks

  • @original_gangsta_
    @original_gangsta_ ปีที่แล้ว +1

    Understood 🔥🔥

  • @prasannasippa5962
    @prasannasippa5962 ปีที่แล้ว

    understood striver thank you!!!

  • @anshulsharma3137
    @anshulsharma3137 2 ปีที่แล้ว +3

    More problems on DSU also coming today ?

  • @sahilpanchasara
    @sahilpanchasara 2 ปีที่แล้ว +4

    Hey striver, in this problem i tried using unionByRank in GFG but it is giving wrong answer. So, we should always use UnionBySize or it has some problem with GFG??
    Thank you

    • @itsaryanb9316
      @itsaryanb9316 2 ปีที่แล้ว

      It's giving me the correct answer using union By Rank

    • @rajchinagundi7498
      @rajchinagundi7498 ปีที่แล้ว

      It does give wrong answer, you have to fix the adjacency matrix indexes, as the node starts from 1, so its 1 based indexing, this will fix your issue, I dont know how strive passed the above test cases, maybe during that time it was zero based indexing.
      DisjointSet ds(V);
      int n=adj.size();
      int m=adj[0].size();
      int id = 1;
      for(int i=0;i

  • @ronaldo-t2d
    @ronaldo-t2d 10 หลายเดือนก่อน

    if we make a set and then store all of it parent element in it and returning the size of set then why is it giving wrong answer?

  • @Chandraprakash-kx4ic
    @Chandraprakash-kx4ic ปีที่แล้ว

    Thank you .. Understood

  • @1tav0
    @1tav0 ปีที่แล้ว

    This was awesome understood

  • @technologybaba192
    @technologybaba192 4 หลายเดือนก่อน

    Understood

  • @The_Shubham_Soni
    @The_Shubham_Soni ปีที่แล้ว

    Understood.

  • @hrushi_borhade
    @hrushi_borhade ปีที่แล้ว

    Understood striver

  • @parshchoradia9909
    @parshchoradia9909 ปีที่แล้ว

    Understood sir!

  • @rishabhthakur5414
    @rishabhthakur5414 4 หลายเดือนก่อน

    understood

  • @niketgupta3884
    @niketgupta3884 2 ปีที่แล้ว

    Hii striver.. Waiting for this.. ☺❣️

  • @-VLaharika
    @-VLaharika ปีที่แล้ว

    Understood 👍

  • @mohdtalib7350
    @mohdtalib7350 ปีที่แล้ว +1

    Java Solution using disjoint set approach is failing the test case in gfg 119 / 121 ; Can any optimization be done in this same approach ?

  • @krishanpratap3286
    @krishanpratap3286 2 ปีที่แล้ว

    Is graph series done?

  • @suryakiran2970
    @suryakiran2970 ปีที่แล้ว

    Understood❤

  • @divyatejaswinivengada6368
    @divyatejaswinivengada6368 10 หลายเดือนก่อน

    understood !!

  • @girikgarg8
    @girikgarg8 ปีที่แล้ว

    Done!

  • @adityasaxena6971
    @adityasaxena6971 ปีที่แล้ว

    Understood Striver

  • @tej.askamble
    @tej.askamble 9 หลายเดือนก่อน

    Done

  • @anshugupta1365
    @anshugupta1365 ปีที่แล้ว

    Understood!!

  • @shreyarawatvlogs6920
    @shreyarawatvlogs6920 9 หลายเดือนก่อน

    idk why but this is showing me segmentation fault. can anyone help me in resolving this?

  • @judgebot7353
    @judgebot7353 ปีที่แล้ว

    understood 👍

  • @p38_amankuldeep75
    @p38_amankuldeep75 ปีที่แล้ว

    understood🔥🔥🔥

  • @many987
    @many987 ปีที่แล้ว +1

    Solution of this video is here.
    class DisjointSet {
    public:
    vector parent, size;
    DisjointSet(int n) {
    parent.resize(n + 1);
    size.resize(n + 1, 1);
    for (int i = 0; i

  • @udaytewary3809
    @udaytewary3809 ปีที่แล้ว

    Understood bhaiya 🙏❤️

  • @KratosProton
    @KratosProton ปีที่แล้ว

    great

  • @himaniupadhyay8201
    @himaniupadhyay8201 ปีที่แล้ว

    US

  • @mohitpargaie4724
    @mohitpargaie4724 ปีที่แล้ว

    Nice

  • @AmanGupta-ib5ss
    @AmanGupta-ib5ss ปีที่แล้ว

    understood :)

  • @pratyakshhhhhhhhhhhhhhhhhhhhh
    @pratyakshhhhhhhhhhhhhhhhhhhhh 10 หลายเดือนก่อน

    🎉🎉

  • @kushagramishra3026
    @kushagramishra3026 2 ปีที่แล้ว

    "Understood"

  • @abhishekkunal8958
    @abhishekkunal8958 หลายเดือนก่อน

  • @gauravghosh6562
    @gauravghosh6562 3 หลายเดือนก่อน

    hello bhaiya, i have a better approach than this, where we have a variable named "components" with an initial value as the number of vertices, we traverse through the adjacent matrix and wherever we see a edge, if the parent of both the nodes involved in the edge are not equal then we combine them by taking union but also decrement the components variabele count by 1 as we are combining two different components into one.By this at the end of our V*V iteration we will have the number of components and simply return it instead of initiating another loop to check if the parent of a node is itself.

  • @codingalley6229
    @codingalley6229 ปีที่แล้ว

    🐐

  • @krishnapalsingh3164
    @krishnapalsingh3164 2 ปีที่แล้ว +7

    1st comment, mujhe 5 LAKH cash chahiye ab striver🤣🤣

  • @addityasharma6426
    @addityasharma6426 2 ปีที่แล้ว

    understood :-)

  • @piyushraj5464
    @piyushraj5464 4 หลายเดือนก่อน

    us

  • @KaushikSharma-c3q
    @KaushikSharma-c3q 2 หลายเดือนก่อน

    ................

  • @saurabhkale4495
    @saurabhkale4495 ปีที่แล้ว +1

    Python code for union find and Number of province
    #User function Template for python3
    class UnionFind:
    # Constructor
    def __init__(self, n_cities):
    self.root = [i for i in range(n_cities)] # tells the root node for each node, initially itself
    self.rank = [1]*n_cities # rank/height of each node
    def find(self, x):
    # find the root of a node x
    if self.root[x] == x:
    return x
    self.root[x] = self.find(self.root[x])
    return self.root[x]
    def union(self, x, y):
    rootx = self.find(x)
    rooty = self.find(y)
    if rootx!=rooty:
    # Check for rank of rootx and rooty. Attach smaller rank graph to larger rank
    if self.rank[rootx] > self.rank[rooty]:
    self.root[rooty] = rootx
    elif self.rank[rooty] > self.rank[rootx]:
    self.root[rootx] = rooty
    else: # the ranks of rootx and rooty are the same
    self.root[rooty] = rootx
    self.rank[rootx]+=1
    def connected(self, x, y):
    # Check wheather 2 nodes are connected or not
    return self.find(x) == self.find(y)

    class Solution:
    def numProvinces(self, adj, V):
    UFObject = UnionFind(V)
    for i in range(len(adj)):
    for j in range(len(adj)):
    if i!=j and adj[i][j] == 1:
    UFObject.union(i, j)

    #make sure that all nodes have the root as the ultimate parent
    for i in range(V):
    UFObject.root[i] = UFObject.find(i)

    return len(set(UFObject.root))

  • @TarunKumarSaraswat
    @TarunKumarSaraswat 12 วันที่ผ่านมา

    thanks

  • @manishpandey2725
    @manishpandey2725 ปีที่แล้ว

    Understood

  • @okaynoobherenoob
    @okaynoobherenoob 5 หลายเดือนก่อน

    understood

  • @ACUCSPRADEEPB-up9ne
    @ACUCSPRADEEPB-up9ne ปีที่แล้ว

    Understood✌️

  • @bhavya8608
    @bhavya8608 ปีที่แล้ว

    understood!!!

  • @girikgarg8
    @girikgarg8 ปีที่แล้ว

    Done

  • @deepakffyt2844
    @deepakffyt2844 2 ปีที่แล้ว

    Nice

  • @manasranjanmahapatra3729
    @manasranjanmahapatra3729 ปีที่แล้ว

    Understood

  • @mriduljain6809
    @mriduljain6809 ปีที่แล้ว

    Understood

  • @kaushalshinde3920
    @kaushalshinde3920 ปีที่แล้ว

    Understood

  • @ajaybind6736
    @ajaybind6736 6 หลายเดือนก่อน

    understood

  • @chiragbansod8252
    @chiragbansod8252 7 หลายเดือนก่อน

    understood

  • @sangeetasharma8574
    @sangeetasharma8574 10 หลายเดือนก่อน

    understood

  • @modiji8706
    @modiji8706 11 หลายเดือนก่อน

    understood

  • @ApnaVlogs-tj7do
    @ApnaVlogs-tj7do ปีที่แล้ว

    understood

  • @YATHARTHBHARDWAJ-y8m
    @YATHARTHBHARDWAJ-y8m ปีที่แล้ว

    understood

  • @YATHARTHBHARDWAJ-y8m
    @YATHARTHBHARDWAJ-y8m ปีที่แล้ว

    understood

  • @amanxsharma
    @amanxsharma ปีที่แล้ว

    understood

  • @rishabhagrawal3133
    @rishabhagrawal3133 ปีที่แล้ว

    understood

  • @jiveshanand5948
    @jiveshanand5948 ปีที่แล้ว

    Understood

  • @amanbhadani8840
    @amanbhadani8840 ปีที่แล้ว

    Understood

  • @mdshohanurrahman4998
    @mdshohanurrahman4998 ปีที่แล้ว

    understood

  • @shivanigupta9747
    @shivanigupta9747 2 ปีที่แล้ว

    Understood

  • @rishabhgupta9846
    @rishabhgupta9846 ปีที่แล้ว

    understood

  • @tanaysingh5348
    @tanaysingh5348 ปีที่แล้ว

    understood

  • @satyamroy3783
    @satyamroy3783 2 ปีที่แล้ว

    understood

  • @Rajat_maurya
    @Rajat_maurya 2 ปีที่แล้ว

    understood

  • @prantikofficial
    @prantikofficial 2 ปีที่แล้ว

    understood

  • @itsaryanb9316
    @itsaryanb9316 2 ปีที่แล้ว

    understood