G-21. Topological Sort Algorithm | DFS

Поділитися
Вставка
  • Опубліковано 6 лип 2024
  • GfG-Problem Link: bit.ly/3PvBfsm
    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
    ---------------------------------------------------------------------------------------------------------------------------

КОМЕНТАРІ • 229

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

    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

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

      Understood

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

      @pulkitjain5159
      0 seconds ago
      LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION
      Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai.
      toh hum dfs ke through bas yeh keh rahe hai ki
      dfs(task , completedTasks){
      visited[task] = true; // mene yeh task karna start kardiya hai
      // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu
      // let task on which my current task is dependend on be "dep".
      for( int dep : adj[ task ] ){
      if(!visited[dep]){
      // agae yeh dep abhi tak khatam nahi hua hai
      dfs(dep , completedTasks); // phele m isko complete kar leta hu
      }
      }
      // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh
      completedTask.push(task);
      }

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

      Why can't we add codes in comments?

  • @srinayan390
    @srinayan390 Рік тому +35

    Many coder who know all this things but cannot explain well, but u r the different beast who can do both single handedly !!!!

  • @decepticonWave
    @decepticonWave Рік тому +65

    The problem with this solution is that if you are given a directed graph that contains a cycle in the solution. The algorithm wont be able to detect, it will spill out an ordering which is wrong. But when using khans algorithm, you will be able to detect whether top. sort was possible or not.

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

      +1

    • @adolft_official
      @adolft_official Рік тому +12

      glad i looked up this cooment, was doing course schedule using dfs topo and getting wrong answer

    • @tanyasingh2344
      @tanyasingh2344 Рік тому +34

      Yeah but he already mentioned it is for Directed Acyclic Graph so it won't work in Graphs containing cycles.

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

      But you can check the size of your topological sort array and if it is equal to number if vertices it is a valid one otherwise not.

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

      C ho tum

  • @harshniteprasad5301
    @harshniteprasad5301 Рік тому +45

    Revising through this playlist before an interview is a bliss.
    INTUITION : incase you faced some trouble , taking in consideration the graph 1->2->3->4
    we start with the dfs(1) we keep calling it for the adjacent nodes and at the very end we reach dfs(4) WHICH DOES NOT HAS ANY ADJ NODE, thus we put it in the stack stating that there is no node it needs to point after completion we push 3 in the stack stating that all the nodes pointed by 3 must already be the stack, same way we go up and at the end we push 1 in the stack stating that all the nodes pointed by 1 are already in the stack in a linear order.
    Linear order if a node v points to u then v comes first then u.

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

      And if it is reverse of topological ordering? Use Queue :P

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

      @@sayandey2492 by playing with where you place stack during recursion you can use stack only.

    • @pulkitjain5159
      @pulkitjain5159 Рік тому +6

      @pulkitjain5159
      0 seconds ago
      LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION
      Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai.
      toh hum dfs ke through bas yeh keh rahe hai ki
      dfs(task , completedTasks){
      visited[task] = true; // mene yeh task karna start kardiya hai
      // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu
      // let task on which my current task is dependend on be "dep".
      for( int dep : adj[ task ] ){
      if(!visited[dep]){
      // agae yeh dep abhi tak khatam nahi hua hai
      dfs(dep , completedTasks); // phele m isko complete kar leta hu
      }
      }
      // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh
      completedTask.push(task);
      }

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

      @@varunaggarwal7126 exactly what i was thinking , the moment you insert the ele should be made at the start and not end , regular dfs is rev topo i guess ?

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

      great comments , it's okk for understanding, actually great but code is actually working in backtracking way, so not exactly fitting......
      mtlb ki phle hum uss element ko khoj rhe hain jo sbpe dependent hain (dfs(1) agar dfs(2) ko call kr rha hain mtlb 1->2 ja skte hain mtlb ki 2 ko krne ke liye 1 ka hona jruri hain, lekin yha hum sbse phle 2 ko stack mein dalenge then 1 ko so that 2 sbse niche chala jaye,) isse jo kaam sbse phle krna hain, jo kisi pe dependent nhi hain wo top pe aajayega@@pulkitjain5159 this is from my understanding, please correct if i am wrong.🙏

  • @arushimathur7205
    @arushimathur7205 10 місяців тому +1

    Great Work Striver. Thanks for always helping us !!

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

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

  • @hah314
    @hah314 11 місяців тому +2

    Can't express it in words, your content is out of the world, really amazing bro❤❤

  • @awesome_latest_virals6098
    @awesome_latest_virals6098 11 місяців тому +9

    we can use bool array instead of int array to mark visited....it will take less memory.

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

    understood, was able to code up using the logic after your explanation, thanks!

  • @SD-vk3ko
    @SD-vk3ko Рік тому +27

    Hey Striver, Thank you for the amazing content. But I request if you could add some problems on Union Find as well. Thanks in advance!!!

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

    Thank you striver for providing such nice content

  • @user-ie8sy7wo4m
    @user-ie8sy7wo4m 10 місяців тому +18

    Quick Tip : If you are thinking, why don't we put into list when you start dfs, this way we don't have to use stack or reverse order. Consider a case 6->0->1->2->3->4->5, we start from 0 and put into list, so ordering comes out to be, 0,1,2,3,4,5 and then we check for 6, so 6 at last, but this is wrong. Hence we cannot put into list when starting the dfs, because we dont' know if 0 was coming from somewhere else. Hence we put into list at last and then reverse(or use stack and pop). So ordering becomes 5->4->3->2->1->0 and then we check for 6, so 5->4->3->2->1->0->6 and reversing this is correct topo.

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

      Thanks bro !!

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

      Why 6 cannot be in last?

    • @user-ie8sy7wo4m
      @user-ie8sy7wo4m 9 місяців тому +1

      @@crosswalker45 Because 6 is at starting of topo sort and not last. It is even before 0, since we started from 0 doesn't mean our topo start from 0.

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

      Thanks

  • @the_curious_engineer
    @the_curious_engineer 22 години тому +1

    whenever your heart is broken , don't ever forget you are golden..

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

    explained in quite easy manner ..thanks habibi

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

    Thank you, STRIVER 🙂

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

    understood,great explanation

  • @Saurabh-fe2bg
    @Saurabh-fe2bg Рік тому +1

    got it!! thanks for this series

  • @suryanshsingh6423
    @suryanshsingh6423 13 днів тому

    Understood. Fantastic explanation❤

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

    loved the intuition and explanation striverr bhaii

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

    Thank you very much. You are a genius.

  • @stith_pragya
    @stith_pragya 7 місяців тому +3

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

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

    Amazingly explained :)

  • @pranayjain._
    @pranayjain._ Рік тому

    Understood! Thank you sir

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

    Awesome work

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

    Thank You sooo much SIR
    🙏

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

    Understood, Thank you so much

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

    understood bhaiya..

  • @pulkitjain5159
    @pulkitjain5159 Рік тому +20

    LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION
    Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai.
    toh hum dfs ke through bas yeh keh rahe hai ki
    dfs(task , completedTasks){
    visited[task] = true; // mene yeh task karna start kardiya hai
    // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu
    // let task on which my current task is dependend on be "dep".
    for( int dep : adj[ task ] ){
    if(!visited[dep]){
    // agae yeh dep abhi tak khatam nahi hua hai
    dfs(dep , completedTasks); // phele m isko complete kar leta hu
    }
    }
    // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh
    completedTask.push(task);
    }

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

      nice explanation

    • @jotsinghbindra8317
      @jotsinghbindra8317 21 день тому

      ek dum sexy explanation bhai!

    • @kunalarora3885
      @kunalarora3885 16 днів тому

      Very clearly explained @pulkitjain5159,
      @striver this is what you call intuition

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

    Thank you sir 😊

  • @user-fx3bn4co5o
    @user-fx3bn4co5o Рік тому

    Its awesome bro

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

    Thank you sir iski bahut need thi. Haal hi mai ek question aaya tha aur woh mai nhi kar paya tha

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

    THANK YOUUU STRIVERRR!!

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

    UNDERSTOOOOOD😊

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

    Understood !

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

    GOD level explanation

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

    understood ❤️

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

    Understood 😊

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 2 місяці тому +1

    Thank you bhaiya

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

    Understood bhaiya

  • @worthlessguy1621
    @worthlessguy1621 2 місяці тому

    understood the assignment :)

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

    UNDERSTOOD!!!!!!!

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

    understoooddddd

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

    Why aren't we using the path[] here? Is it because its acyclic graph?

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

    understood!!! JOD

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

    understood!

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

    Understood❤

  • @per.seus._
    @per.seus._ 5 місяців тому +1

    understoood

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

    UNDERSTOOD.

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

    everything is nyc except one thing sir if suppose i/p is loop(1,2,3) then s.size==n fails only bfs accepts am i correct i chckd for conditions

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

    Understood.

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

    Understood !!

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

    can we pushback the node in ans in the postorder of the dfs function i.e., after the for-loop?

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

      then you have to reverse the stack.

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

      ua-cam.com/video/6Vi5Td_a8B8/v-deo.html&ab_channel=Pepcoding watch this for your doubt clarification

  • @1tav0
    @1tav0 Рік тому

    Awesome! Us

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

    Understood:)

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

    Understood

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

    Awesome

  • @ayushgaurabh8604
    @ayushgaurabh8604 26 днів тому

    awesome

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

    maza aa gya

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

    What I understood from this problem is that "GIve a BFS path using DFS". Is it?

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

    hey striver I want to code like you!!

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

    understood

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

    Cool understood

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

    understood.

  • @shivendrasingh8520
    @shivendrasingh8520 19 днів тому

    can we use queue in this question at last we will reverse the queue

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

    UNDERSTOOD

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

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

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

    Can someone help me understand how he determines if we are given an adj matrix or an adj list?

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

      If given
      vectoradj; that mean we have an adj matrix
      If given
      vectoradj[ ] this mean we have an adj list

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

      @boomsi69 tompr ko mera pranam 🙏🙏

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

    yes

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

    Even without taking a stack we can do, it is by taking a vector and storing all the node values after completion of that node's dfs, and finally reverse that vector...

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

      Why to go all the way to reverse a vector rather than storing it in the reverse order during the dfs. Just create a vector with size of total number of nodes and using a index variable move from the back of vector to the front during dfs. Here's how its done:
      class Solution
      {
      private:
      void dfs(int start,int vis[],vector adj[],vector& ans,int& index){
      vis[start]=1;
      for(auto it: adj[start]){
      if(!vis[it]){
      dfs(it,vis,adj,ans,index);
      }
      }
      ans[index--]=start; // Its decrement
      }
      public:
      //Function to return list containing vertices in Topological order.
      vector topoSort(int V, vector adj[])
      {
      // code here
      int vis[V]={0};
      vector ans(V);
      int index=V-1;
      for(int i=0;i

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

    is it ok to use queue rather than using a stack ?

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

      Yes but at last when you pop out nodes, you will have to reverse the resultant list.

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

      @@Shivanai_h thank you 😊

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

      @Ayush Negi simply use vector, and reverse it. No need to store again to vector from deque while returning.

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

    Hey Striver ( @takUforward ) is topological sort used by dependency management tools like Maven or Gradle to manage project dependencies??

  • @amanasrani6405
    @amanasrani6405 2 місяці тому

    understand bhaiya❤🙏🏻\

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

    Understood..

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

    @take U forward before applying this method we should ensure that no cycle is present ??

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

      Input is always DAG, so it's not checked. But if input can be cyclic graph, you need to add cycle checks

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

      @@VIRAJBHOSLE Yeah, thanks!!!

  • @AdityaKumar-uf5xp
    @AdityaKumar-uf5xp Рік тому +1

    understood but striver I forgot those code and have to remember everytime . How should I keep remember the code?

    • @diksha3157
      @diksha3157 Рік тому +6

      Don't memorise the code. Instead, try to understand the logic and then write code. Converting logic into code requires practice.

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

      Memorize the logic. If DFS, and topological sort, use a stack. BFS, use Queue. Both use visited array

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

    I believe we need to assume that the given directed graph does not contain any cycle, only then this algorithm using DFS will work.

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

    grt vdo

  • @Chandraprakash-kx4ic
    @Chandraprakash-kx4ic Рік тому

    understood :D

  • @user-bc6ss6gp3z
    @user-bc6ss6gp3z 3 місяці тому

    #Striver rocks 🤟👍

  • @UmeshYadav-qx4hr
    @UmeshYadav-qx4hr 6 місяців тому

    link is not found for -C++/Java/Codes and Notes Link
    Please check.

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

    what if i run this algo on a directed graph with cycle

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

      Topological Sorting - DFS algorithm will print wrong linear ordering if input is a directed cyclic graph.

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

    Why can we not use simple array instead of stack. I am not able to understand of specific stack in this case. Can any body clear this?

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

      Yes we can push into vector.....
      Than at the end we can reverse it

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

    how do we know that stack will be used

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

      Because we need to get in reverse order

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

      @@narendrarokkam5367 we can store it in a vector then simply reverse it, space saved right?

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

      @@soumyamondal but time inc

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

    4:05 - 7:50

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

    Understood but what the intuition ?

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

    only had to watch half of the video and did the coding part all by myself

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

    🐐

  • @soicooc3500
    @soicooc3500 2 місяці тому

    5:30

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

    how cycle is handled in this code?

  • @soicooc3500
    @soicooc3500 2 місяці тому

    4:08

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

    6:20

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

    "UNDERSTOOD"

  • @shubhranginidas6818
    @shubhranginidas6818 2 місяці тому

    We should apply the DFS way of Topological Sorting only if the ordering of the resulting sort is checked otherwise should always prefer BFS way of Topological Sorting. WHY?
    Because if the cycle exists DFS would return all the vertices with wrong ordering but in case of BFS, it wouldn't return all the vertices if cycle exists. So even if we don't go for ordering detection, number of vertices itself would clear whether sorting is possible or not.
    This is the reason why BFS (Kahn's Algorithm) is preferred.

  • @rayyansyed2998
    @rayyansyed2998 8 місяців тому

    "understood"

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

    457310 aa sakta hai final output?

  • @evilpollination1916
    @evilpollination1916 2 місяці тому

    Understood Striver bhai. Aapne samjhaya hai toh samjh to aayega.
    Also bhai aapki tabayt kharab lag rahi thi . Pls take care bhai.

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

    Understood Striver

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

    UnderStood

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

    US, 900th like

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

    is Indegree logic wrong in dfs? umm why?>
    vectorans;
    void dfs(int src, vectorgraph[] , vector&inDeg , vector&vis){
    vis[src]=1;
    ans.push_back(src);
    for(auto nbr: graph[src]){
    inDeg[nbr]--;
    if(inDeg[nbr] == 0 && vis[nbr]==0){
    dfs(nbr,graph,inDeg,vis);
    }
    }
    }
    vector topoSort(int n, vector graph[])
    {
    vectorinDeg(n,0);
    for(int i=0;i