G-17. Bipartite Graph | BFS | C++ | Java

Sdílet
Vložit
  • čas přidán 6. 09. 2024
  • GfG-Problem Link: bit.ly/3SQQgId
    C++/Java/Codes and Notes Link: takeuforward.o...
    DP Series: • Striver's Dynamic Prog...
    SDE Sheet: takeuforward.o...
    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.geeks...
    Code "takeuforward" for 20% off on sys-design: get.interviewr...?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/inv...
    Take 750 rs free Amazon Stock from me: indmoney.oneli...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v...
    Linkedin/Instagram/Telegram: linktr.ee/take...
    ---------------------------------------------------------------------------------------------------------------------------

Komentáře • 196

  • @takeUforward
    @takeUforward  Před 2 lety +52

    Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too, you don't 😞
    Do follow me on Instagram: striver_79

  • @ayushkumarverma2237
    @ayushkumarverma2237 Před 2 lety +283

    just want to thanks bhai, yesterday i got selected in 14 lpa package, you will always be one of the major reasons for my selection.

    • @aniruddhadas1778
      @aniruddhadas1778 Před 2 lety +1

      As a fresher?

    • @ayushkumarverma2237
      @ayushkumarverma2237 Před 2 lety +4

      @@aniruddhadas1778 Yeah

    • @imskr2683
      @imskr2683 Před 2 lety

      congratulations bro😍😍😍

    • @sdexstarlord
      @sdexstarlord Před rokem

      can you please tell me why my code is giving tle ??
      bool check(vectorcolor , int start , vectoradj[]){
      queueq;
      q.push(start);
      color[start] = 0;
      while(!q.empty()){
      int x = q.front();
      q.pop();
      for(auto &i:adj[x]){
      if(color[i] == -1){
      color[i] = !color[x];
      q.push(i);
      }else if(color[i] == color[x]){
      return false;
      }
      }
      }
      return true;
      }
      bool isBipartite(int V, vectoradj[]){
      vectorcolor(V , -1);
      for(int i = 0 ;i

    • @-Corvo_Attano
      @-Corvo_Attano Před rokem +1

      congrats Brother :)💞

  • @rikudosennin
    @rikudosennin Před 2 lety +65

    Striver I grinded DSA in the last few months, referred to your videos whenever in doubt. I just got my internship in a really good company ! Much love ❤️

  • @shreyanshmittal9381
    @shreyanshmittal9381 Před rokem +16

    *colour the src node as 0
    *push src node into queue
    *check for adjacents :
    *if adjacent has not been coloured, colour it opposite to current node and push it into queue
    *else check if current node colour is same as adjacent node colour, if yes return false

  • @nishanth_cf
    @nishanth_cf Před 4 dny +1

    Equivalent definitions of a bipartite graph:
    1)There is no cycle of odd length
    2)A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.(leetcode description)
    3).The graph should be bi-colourable.

  • @tasneemayham974
    @tasneemayham974 Před 6 měsíci +5

    AMAAAZZZINNGGGG AS ALWAYYSSSS STRIVERRR!!!
    And for those who have difficulties in the LeetCode version, this is how it ran using my Java Code:
    class Solution {
    public boolean isBipartite(int[][] graph) {
    int n = graph.length;
    int[] colors = new int[n];
    Arrays.fill(colors,-1);
    for(int i=0; i

  • @codenchill732
    @codenchill732 Před 2 lety +9

    Omg. Video at this time . Hats off to your
    Work 👏👏

  • @amansinghal4663
    @amansinghal4663 Před rokem +9

    Space = O(n) + O(n)
    Time = O(n) * [O(n)+O(2E)]

    • @verma_jay
      @verma_jay Před 10 měsíci +3

      Time complexity is wrong
      It will be O(n) + O(n + 2E) as you are not doing full bfs each time in the outer loop

  • @yogesh_ok
    @yogesh_ok Před 2 měsíci +1

    great explanation ... very easy to understand

  • @coding8000
    @coding8000 Před rokem +1

    Bhai tu bhagwan h, mere liye, tujhe yaad karke, ek umeed jagti h, called "Let's try one more time", thanks buddy keep helping.

  • @stith_pragya
    @stith_pragya Před 9 měsíci +1

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

  • @abdulrhmanmagdy7591
    @abdulrhmanmagdy7591 Před rokem +1

    Thanks bro, but in check function, you have to use call by reference(&) for array color to save the changes in other function.

  • @MMNayem-dq4kd
    @MMNayem-dq4kd Před rokem +1

    Understood,sir.Very clear explanation.

  • @vigneshpugaz8308
    @vigneshpugaz8308 Před rokem +4

    Hey striver! This is a very cool series to revise your concepts. Here you missed a case where there's a self loop at a node.

  • @jagratgupta8392
    @jagratgupta8392 Před rokem +1

    understood sir really nice explaination ............just simply brute force.........

  • @satishsingh8297
    @satishsingh8297 Před rokem

    Understood bhaiyya, I was able to solve this problem by myself, it is quite similar to finding a cycle in a graph, just a few changes in the code. Thankyou so much

  • @user-xc1xq1vb1m
    @user-xc1xq1vb1m Před rokem

    u make every topic so easy... thanks a lot

  • @user-kl3qv1sc8k
    @user-kl3qv1sc8k Před 3 měsíci

    Understood striver, thanks a lot!!

  • @KalingaAbhisek
    @KalingaAbhisek Před rokem +1

    Understood. The previous correction I did was silly. It was correct.
    Loving the graph series bhaiya ❤❤
    Thank you for this series ❤🙏

  • @pixldesigns5589
    @pixldesigns5589 Před 7 měsíci

    Able to solve it on my own all thnks to u😊

  • @cinime
    @cinime Před 2 lety

    Understood! Super amazing explanation as always, thank you very much!!

  • @vakhariyajay315
    @vakhariyajay315 Před rokem +1

    Thank you very much.Yoy are a genius.

  • @priyanshkumar17
    @priyanshkumar17 Před 3 měsíci

    amazing explanation as always...

  • @sumerrawat6947
    @sumerrawat6947 Před 2 lety +4

    Is there any way to detect cycle in a graph and find if its odd length or even ?
    -> then we will return true if even , and false if odd

    • @aeroabrar_31
      @aeroabrar_31 Před rokem

      He already made videos on how to detect a cycle by using both bfs and dfs..
      We can keep count variable to keep track of length i guess..
      Try it out once it will be super excited experience.

    • @studyonline3236
      @studyonline3236 Před rokem +11

      @@aeroabrar_31 you cannot directly use a counter to track the length, as in the methods discussed, we just check if the adj is already visited or not. What if the graph has a cycle somewhere in between? How would you use the above methods to find the starting point of a cycle(from where the counting should be done)?

  • @ishangujarathi10
    @ishangujarathi10 Před rokem

    youre a geniuss striverr!!! tysm

  • @abhiharshchauhan4489
    @abhiharshchauhan4489 Před 8 měsíci

    understood ,as always great explanation

  • @codeand8212
    @codeand8212 Před rokem

    thanku so much for these quality
    lectures

  • @DevashishJose
    @DevashishJose Před 7 měsíci

    Understood thank you so so much.

  • @UECAshutoshKumar
    @UECAshutoshKumar Před rokem +1

    Thank you sir 😊

  • @vakhariyajay2224
    @vakhariyajay2224 Před rokem

    Thank you very much. You are a genius.

  • @imskr2683
    @imskr2683 Před 2 lety +4

    25 din baad placement start ho rhe h mere yha pr aur kya hi kismat h bhai.

  • @adnan.
    @adnan. Před 11 měsíci +1

    can we initialize the element in the color array by int color[V] = {-1}; instead of looping over the entire array and changing index by index?

    • @aniketsingh9734
      @aniketsingh9734 Před 8 měsíci

      use vector and pass -1 in constructor or use memset for arrays

  • @rakshitdevra7060
    @rakshitdevra7060 Před rokem

    Wonderful explanation

  • @firenoms7809
    @firenoms7809 Před rokem

    understood to the core

  • @Flynn-lk8im
    @Flynn-lk8im Před rokem

    using *_enums_* will make it much more intuitive.

  • @harshvardhansingh2272
    @harshvardhansingh2272 Před 2 lety

    understood striver
    as always great explanation

  • @nikhilmittal4378
    @nikhilmittal4378 Před 9 měsíci +1

    understood

  • @rishabhgupta9846
    @rishabhgupta9846 Před rokem

    understood,great explanation

  • @sauravchandra10
    @sauravchandra10 Před rokem

    Understood, thanks!

  • @coolgaurav5163
    @coolgaurav5163 Před 29 dny

    Understood

  • @KratosProton
    @KratosProton Před 2 lety

    Great explaination

  • @sumitchakrabortystudy651

    understood completely

  • @_hulk748
    @_hulk748 Před rokem

    Thankyou sir understood🙇‍♂❤🙏

  • @user-vi9dz4ix8v
    @user-vi9dz4ix8v Před rokem

    UNDERSTOOD!!!!!

  • @abhishek__anand__
    @abhishek__anand__ Před rokem

    Nice Explanation

  • @sumitworld918
    @sumitworld918 Před 6 měsíci

    Understood ❤

  • @amanbhadani8840
    @amanbhadani8840 Před rokem +1

    Missing your baap-beta concept bhaiya in this new graph series.Overall everything is really good.

  • @PrimeContent01
    @PrimeContent01 Před 11 měsíci

    I understood but there are flaws in the code u done ,but i understood the concept.

  • @hashcodez757
    @hashcodez757 Před 11 měsíci

    understood bhaiya!!

  • @aryankumarsingh6060
    @aryankumarsingh6060 Před rokem

    bhut acha padhate ho sir

  • @The_Shubham_Soni
    @The_Shubham_Soni Před rokem

    UNDERSTOOD.

  • @HarshaVardhan-hr2es
    @HarshaVardhan-hr2es Před 10 měsíci

    Thank you striver 😭😭

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l Před 4 měsíci

    Thank you Bhaiya

  • @andresfgalvis2010
    @andresfgalvis2010 Před rokem

    understood, thanks a lot

  • @sanketh768
    @sanketh768 Před rokem +2

    So we have only 2 choice for the Colors?

  • @-VLaharika
    @-VLaharika Před rokem

    Understood👍

  • @ANURAGSINGH-nl2ll
    @ANURAGSINGH-nl2ll Před 11 měsíci

    understand thank you

  • @gautamsaxena4647
    @gautamsaxena4647 Před 3 měsíci

    understood bhaiya

  • @herculean6748
    @herculean6748 Před rokem

    thanks striver🙌

  • @atharvadeshmukh6328
    @atharvadeshmukh6328 Před 6 měsíci

    Understood!

  • @RS-zh1vc
    @RS-zh1vc Před rokem

    Thank you 🙂

  • @adityasaxena6971
    @adityasaxena6971 Před rokem

    Understood💯💯💯

  • @farazjawaid2982
    @farazjawaid2982 Před rokem

    understood broskki !!

  • @prashusahu6610
    @prashusahu6610 Před rokem

    Understood 😃

  • @original_gangsta_
    @original_gangsta_ Před rokem

    Understood 😄😄

  • @beinghappy9223
    @beinghappy9223 Před rokem +1

    Code failing on larger testcases means component ka lafra

  • @ayushgaurabh8604
    @ayushgaurabh8604 Před 3 měsíci

    awesome

  • @gautamsolanki6022
    @gautamsolanki6022 Před rokem +1

    Always 💯💯💯💯💯

  • @prepmee
    @prepmee Před rokem

    understood 🔥

  • @akashsahu2571
    @akashsahu2571 Před rokem

    yes

  • @suhaanbhandary4009
    @suhaanbhandary4009 Před rokem

    understood!!

  • @ashishbhardwaj4334
    @ashishbhardwaj4334 Před rokem

    Understood..

  • @kunaljain6932
    @kunaljain6932 Před rokem +1

    I was able to understand that odd length cycle will not be bipartite. Without any external help

  • @prajwalhorti3717
    @prajwalhorti3717 Před rokem

    understood!

  • @-Corvo_Attano
    @-Corvo_Attano Před rokem

    Understood :)

  • @p38_amankuldeep75
    @p38_amankuldeep75 Před rokem

    understood💙💜💙

  • @oqant0424
    @oqant0424 Před rokem

    understood!!!!!!!!!!!

  • @ayushkumar-bj6fb
    @ayushkumar-bj6fb Před rokem

    What is time complexity when graph have N node and N connected components

  • @darshanpatel9131
    @darshanpatel9131 Před 7 měsíci +2

    i guess the same solution in Leetcode is giving TLE.....

    • @srawat1007
      @srawat1007 Před 21 dnem

      #include
      #include
      using namespace std;
      class Solution {
      public:
      bool isBipartite(vector& graph) {
      int n = graph.size();
      vector col(n, 0); // 0 - unvisited, 1 - color 1, 2 - color 2
      queue q;

      for (int i = 0; i < n; i++) {
      if (col[i] == 0) { // Not visited
      q.push(i);
      col[i] = 1; // Start coloring the first node with color 1

      while (!q.empty()) {
      int t = q.front();
      q.pop();
      int validcol = (col[t] == 1) ? 2 : 1; // Toggle color

      for (int neighbor : graph[t]) {
      if (col[neighbor] == 0) { // Not visited
      col[neighbor] = validcol; // Color with valid color
      q.push(neighbor);
      } else if (col[neighbor] == col[t]) { // Same color as current node
      return false; // Not bipartite
      }
      }
      }
      }
      }

      return true; // All components are bipartite
      }
      };correct sol

  • @Hound77
    @Hound77 Před 2 lety +1

    🔥🔥

  • @sripriyapotnuru5839
    @sripriyapotnuru5839 Před rokem

    Thank you, Striver 🙂

  • @anshusharma11
    @anshusharma11 Před rokem

    The only thing I am not getting is why we are doing BFS for every node in graph if it's not colored before? Is this because the graph can be in the form of connected components? Why cant we do the way we did for finding cycle, add the root node and then keep going from there.

    • @saitrinathdubba
      @saitrinathdubba Před rokem

      Graph can have connected components in it. For reference you can look into LC question which is much more detailed than GFG.

  • @armaanhadiq3741
    @armaanhadiq3741 Před 4 měsíci

    What is the chromatic number of the graph, Is it somehow related to the coloring of the graph?

  • @naveenapatnaik9795
    @naveenapatnaik9795 Před 6 měsíci

    Where is the component logic video link ?

  • @addityasharma6426
    @addityasharma6426 Před rokem

    understood :-)

  • @rayyansyed2998
    @rayyansyed2998 Před 11 měsíci

    "understood"

  • @shreyasingh1960
    @shreyasingh1960 Před rokem +1

    hey, in 785 ques leetcode, what is the given parameter "graph" is?? its weird some set thing is going on

    • @krishgupta4408
      @krishgupta4408 Před rokem +1

      its given in matrix form not in list.... but if u will go on gfg u will find the same question in list form
      as striver solved in the video

    • @deviprasad_bal
      @deviprasad_bal Před rokem +3

      it's the same thing like adjacency list, just the index represents the u and its components as v. Like,
      graph = [[1,2,3],[0,2],[0,1,3],[0,2]] means
      0 : {1,2,3}
      1 : {0,2}
      2 : {0,1,3}
      3 : {0,2}
      my code for this problem is as :
      bool bfs(int i, vector& graph, vector& col) {
      queueq;
      q.push({i,1});
      col[i] = 1;
      while(!q.empty()){
      pairp = q.front();
      q.pop();
      for(auto it: graph[p.first]){
      if(col[it]==-1){
      col[it] = !p.second;
      q.push({it,col[it]});
      }
      else if(col[it]==p.second){
      return false;
      }
      }
      }
      return true;
      }

      bool isBipartite(vector& graph) {
      int n = graph.size();
      vector col(n,-1);
      for(int i=0;i

    • @shreyasingh1960
      @shreyasingh1960 Před rokem

      @@krishgupta4408 thankyou!!

    • @shreyasingh1960
      @shreyasingh1960 Před rokem

      @@deviprasad_bal thankyou so much!!

    • @NAMAN-wj7dj
      @NAMAN-wj7dj Před 4 měsíci

      @@deviprasad_bal thanks man !!

  • @yashwanthallumilli603
    @yashwanthallumilli603 Před 2 lety +1

    Striver bro can you please share your timings you follow .at 3.30 u r uploading u r video,why do u sleep brother ?🤔

  • @googleit2490
    @googleit2490 Před rokem

    Beware in using vis/color vector...
    Sep'5, 2923 11:41 pm

  • @GungunRamchandani
    @GungunRamchandani Před měsícem

    Understood

  • @AbhishekThakur-1040
    @AbhishekThakur-1040 Před 2 lety +1

    1st view💖

  • @thaman701
    @thaman701 Před 2 měsíci

    Op

  • @NishantRaj-pf5du
    @NishantRaj-pf5du Před rokem

    US

  • @ajitpalsingh606
    @ajitpalsingh606 Před 5 měsíci

    ok

  • @manasranjanmahapatra3729

    UnderStood

  • @aysams2
    @aysams2 Před 11 měsíci

    03:50 - Hey people, you watched 'Evil Dead Rise' movie?

  • @ishita__code
    @ishita__code Před 7 měsíci

    can anybody send the correct code of this i am getting error at color

  • @arkasheikh3539
    @arkasheikh3539 Před rokem

    "UNDERSTAND"

  • @shadow_was_here
    @shadow_was_here Před rokem

    Python solution (BFS):
    from collections import deque
    class Solution:
    def isBipartite(self, V, adj):
    #code here
    def bfs(src, vis):
    vis[src] = "0"
    q = deque()
    q.append(src)
    while q:
    node = q.popleft()
    for adjNode in adj[node]:
    if vis[adjNode] == -1:
    vis[adjNode] = "0" if vis[node] == "1" else "1"
    q.append(adjNode)
    elif vis[adjNode] == vis[node]:
    return False
    return True
    vis = [-1]*V
    for i in range(V):
    if vis[i] == -1:
    if not bfs(i, vis): return False
    return True

    • @mradulchourasiya3868
      @mradulchourasiya3868 Před rokem

      I was using nearly same code, but using 0s and 1s instead of strings of 0s and 1s but it was not working, I copied striver's code but still it was not working, can you tell if using strings helps or just my code was trash:
      Here is my code:
      from collections import deque
      class Solution:
      def check(self, start, adj, V, colored):
      q = deque()
      q.append(start)
      colored[start] = 0
      while q:
      node = q.popleft()
      for i in adj[node]:
      if colored[i]==-1:
      colored[i]=(~(colored[node]))
      q.append(i)
      elif colored[i]==colored[node]:
      return False

      return True

      def isBipartite(self, V, adj):
      colored = [-1 for i in range(V)]
      for i in range(V):
      if colored[i]==-1:
      if self.check(i, adj, V, colored)==False:
      return False
      return True

  • @051-avnee4
    @051-avnee4 Před rokem

    US :) !!