Course Schedule | Deadlock detection | Graph coloring | Leetcode

Sdílet
Vložit
  • čas přidán 6. 09. 2024
  • This video explains a very important programming interview problem which is, given a course schedule with prerequisites for each course, find if it is possible to take all the courses satisfying the prerequisites for each course. If it is possible then return TRUE otherwise FALSE.This problem is same as detecting a deadlock in a single resource instance distributed system.In such a system, if we have a cycle then we a deadlock.Therefore, this problem further reduces to finding cycle in a graph.I have shown the solution using graph coloring to detect cycle in a directed graph.At the end of the video, i have explained the CODE. CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    =================================================================
    INSTAGRAM: / surya.pratap.k
    LinkedIn: / surya-pratap-kahar-47b...
    =================================================================
    CODE LINK: gist.github.co...
    SIMILAR PROBLEMS:-
    Detect cycle in a directed graph: • Detect cycle in a dire...
    Detect cycle in an undirected graph: • Detect cycle in an und...

Komentáře • 114

  • @anshitmishra
    @anshitmishra Před 4 lety +48

    Sir, your videos are really helpful than a Paid Course❤

  • @genctasbasi
    @genctasbasi Před 3 lety +17

    Another great one. He's my new favourite.

  • @mrunaldave6781
    @mrunaldave6781 Před 3 lety +5

    Overcomplicated with three colors. Why can't we simply use a boolean visited array and from each node to check if the current node was already included in the traveling path.

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Your wish :)

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

      @@techdose4u can we not use logic used for cloning graph ? where we look for visited node, in this case as well we can do near to similar approach ? tree/graph problems are near to similar but why choose different way of solving ? we can do with minimal changes.

  • @abcdeereijgfhd3215
    @abcdeereijgfhd3215 Před 3 lety +4

    just a note if you had a processing state as 1 and processed one as 2 would be more understandable since it is in increasing order. BTW nice explanation. Good effort.

  • @livingston8267
    @livingston8267 Před 3 lety +1

    Dude.. You are better than all of college lectures..

  • @rahulchudasama9363
    @rahulchudasama9363 Před 3 lety +3

    Thanks a ton. Now I am able to solve the same problem using DFS and BFS.

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

    A very similar way for using the unvisited, processing and processed is to use white - grey - black colors respectively

  • @rakshith3547
    @rakshith3547 Před 3 lety +1

    I have coded this in Java. Posting my code below.
    class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
    // to make adj matrix take ie Graph representation : (Adjacency list)
    List output = new ArrayList();
    /*We convert the list of course pairs to a directed graph with an edge u->v that represents a "pre-requisite to" relationship. Thus if we have the pair [0,1] (1 is a pre-requisite to 0), then we will have the following edge in our graph : 1->0
    //Note: We consider the adjacency list representation over an adjacency matrix, considering that the graph might be sparse.*/
    for(int i=0;i 1
    1 > 2
    2 > 3
    so , in the following loop we build this
    */
    for(int[] prereq : prerequisites) {
    int coursePrequisite = prereq[1];
    int currentCourse = prereq[0];
    List prqCourses = output.get(currentCourse);
    prqCourses.add(coursePrequisite);
    }
    /*
    we use color coding in graph
    following are the indications
    0 : unvisited
    1 : processed
    2 : processing
    */
    int[] visited = new int[numCourses];
    // for every node(which represents a course) in the graph
    for(int i=0;i

  • @saunaknandi1814
    @saunaknandi1814 Před 2 lety +2

    At first it took a lot of time but I am happy I made it,

  • @hemanthram4369
    @hemanthram4369 Před 4 lety +4

    Keeping going sir... Very helpful posts🙏🙏♥️

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Thanks :)

    • @nishanksoni7120
      @nishanksoni7120 Před 4 lety

      @@techdose4u Can you please check the playlists once.The playlists contains repetitive videos and increases the count.

  • @ShivamKhantwal94
    @ShivamKhantwal94 Před 2 lety +3

    Sir why u used processed and processing
    Why not simple cycle detection

  • @Firstusee256
    @Firstusee256 Před 4 lety +4

    Well, we can also implement it using in degree I.e topological sort..

  • @radhu8
    @radhu8 Před 3 lety +3

    Yet another amazing video! Thank you

  • @anupriyanishad
    @anupriyanishad Před 3 lety +2

    Best explanation... Thanks a lot for investing your time in spreading knowledge.

  • @rt_developer
    @rt_developer Před 4 lety +5

    It would be more clear if there is an example of graph containing a cycle. Anyways your explanation is awesome 🙌

    • @techdose4u
      @techdose4u  Před 4 lety +3

      U dint give it because I don't want to explain how to find cycle. My main intention was to explain why are we using 3 states 0,1,2. Cycle finding is already explained in other videos.

  • @alexb6568
    @alexb6568 Před 3 lety +1

    The arrows are drawn in the wrong direction.

  • @SudhirKumar-sg8yt
    @SudhirKumar-sg8yt Před 3 lety +1

    Your explanation us very good , It would be helpful if you explain Time and Space complexity too.

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

    Java solution (Your runtime beats 100.00 % of java submissions)
    class Solution {
    public boolean iscyclic(ArrayList[] graph,int[] visit,int curr)
    {
    if(visit[curr]==2)
    return true;
    visit[curr]=2;
    for(int i=0;i

    • @techdose4u
      @techdose4u  Před 4 lety

      Nice 👍

    • @AvikNayak_
      @AvikNayak_ Před 2 lety

      MY PROGRAM:
      class Solution {
      public boolean canFinish(int numCourses, int[][] prerequisites) {

      if(numCourses ==0 || prerequisites.length == 0)
      {
      return true;
      }

      HashMap map = new HashMap();
      for(int i=0;i

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

    Excellent sir 👏

  • @stevethebeve7
    @stevethebeve7 Před 2 lety

    If course A requires course B to be a prerequisite, it should be course B pointing to course A, not the other way around. (B --> A).

  • @umeshpatidar1837
    @umeshpatidar1837 Před 3 lety +1

    why we need graph , it should be solved by linkedlist cycle detection? there is no mention of multiple prerequisites course for a course

  • @AINeptune
    @AINeptune Před 2 lety

    you are a amazing professor

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

    👌👌👌👌Very clear👌👌👌👌

  • @th2315
    @th2315 Před rokem

    this tutorial is amazing!

  • @RahulVerma-fz2jf
    @RahulVerma-fz2jf Před 3 lety +1

    Awesome One. Your way of explaining the problem, by breaking it down is really good. Keep up the good work.

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

    Time and Space Complexity?

  • @apoorv7361
    @apoorv7361 Před 3 lety +1

    great video sir ! Thx u made it so simple

  • @ABHISHEK-fy1in
    @ABHISHEK-fy1in Před 4 lety +1

    Using Topological Sort ->
    class Solution {
    public:
    bool canFinish(int n, vector& pre) { // n = no of vertices
    int edge=pre.size();
    vector< vector > adj(n,vector ());
    vector< int > indegree(n,0); // incoming edges on a vertex
    for(int i=0;i

  • @Amit_Kumar_1999
    @Amit_Kumar_1999 Před 4 lety +1

    I also used the same approach, but instead of an array, I maintained two set processing, processed. But I think using Kahn's algorithm we can get a more optimized solution.

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Kahn's algo is also traversing each node and processing so the time should be same as this one.

  • @shrad6611
    @shrad6611 Před 3 lety

    Solution in Java
    class Solution {
    public boolean canFinish(int n, int[][] pre) {
    ArrayList arr =new ArrayList();

    for(int i = 0; i

  • @manishankarbolli
    @manishankarbolli Před 3 lety

    No Failing case was discussed

  • @kapil4457
    @kapil4457 Před 2 lety

    What if there are multiple components of a graph??

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

    not able to understand the code of line 25. how the directed graph is created ??please reply sir

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

      Actually we are given a 2D array where we have 2 cols. 1st col is source and 2nd col is destination. I am just making an array of linked list where I am assuming the array index to be source and pushing the destination into the linked list. This keeps track of all adjacent nodes where they are destination and curr node is source. Please read adjacency list for clarity.

    • @mandeep2192
      @mandeep2192 Před 4 lety

      @@techdose4u thnku i got it..i was confused b/w vector of vectors and adjacency matrix..

  • @manishkumar-qn6lx
    @manishkumar-qn6lx Před 2 lety

    Hey, I have a doubt...
    If we use DFS for the given problem (3 --> 2 --> 0 --> 1) & let's assume there is a loop in between (3-->0) and the source node is 0, at the time when we reach node 3 after recursion, node 2, 0 & 1 will already be marked as PROCESSED. How we will find if there is a loop in between node 3 and node 0?
    According to the explained logic, the node should be in PROCESSING state and if got visited again then we will consider this as loop.

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

    instead of putting all questions in one playlist(interview programming questions),please make separate playlist topic wise

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

      Topicwise playlists are also present.

    • @nishanksoni7120
      @nishanksoni7120 Před 4 lety +1

      @@techdose4u Can we have basics too.Because graphs are completely naive for some peoples

    • @techdose4u
      @techdose4u  Před 4 lety

      Yep...I will continue with graphs once leetcode challenges are over 😅

  • @nvntsingh
    @nvntsingh Před 3 lety +1

    Why do you prefer adjacency matrix representation over adjacency list?

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Beginner friendly maybe :) I always solve with list and not matrix.

  • @shreshthsingh7744
    @shreshthsingh7744 Před 3 lety +1

    Nice Videos, But Sir please add some more ads , your video interrupts the ads. :D

    • @techdose4u
      @techdose4u  Před 3 lety

      😂 I set to auto-generation mode. Please understand that free content will have to contain ads for sustainability.

  • @prarthanakandwal6625
    @prarthanakandwal6625 Před 4 lety +1

    Can you please explain the creation of directed graph once more?

  • @newtanagmukhopadhyay4716

    bro can you please tell me why doesnt my code give the correct ans ? first i detected if there is a cycle in the directed graph. if yes then return blank array otherwise then i simply did topological sort and returned the answer. here is my code : findOrder is the main function here.
    vectorans;
    bool cycle(int node,vector&visited,vector&stack,vectoradj[])
    {
    visited[node]=true;
    stack[node]=true;
    for(int neighbour:adj[node])
    {
    if(visited[neighbour]==false)
    {
    if(cycle(neighbour,visited,stack,adj))
    return true;
    }
    else if(stack[neighbour]==true)
    {
    return true;
    }
    }
    stack[node]=false;
    return false;
    }
    void topological_sort(int node,vector&visited,vectoradj[])
    {
    visited[node]=true;
    for(int neighbour:adj[node])
    {
    if(visited[neighbour]==false)
    {
    topological_sort(neighbour,visited,adj);
    }
    }
    ans.push_back(node);
    }
    vector findOrder(int V, int m, vector prerequisites)
    {
    bool iscycle=false;
    vectoradj[V];
    for(auto edge:prerequisites)
    {
    adj[edge[0]].push_back(edge[1]);
    adj[edge[1]].push_back(edge[0]);
    }
    //PART 1 : Find out if cycle exists in this using kahn algorithm. if yes,then it is not possible.
    vectorvisited(V,false);
    vectorstack(V,false);
    for(int i=0;i

  • @vamsia5543
    @vamsia5543 Před 4 lety +3

    It was a great tutorial sir. Can we apply the cycle detection algorithm used in an undirected graph ( by removing bidirectional edges )for this problem as well sir.?

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

      I have already explained why we need directed graph in the video. Please follow that.

    • @vamsia5543
      @vamsia5543 Před 4 lety +1

      ​I meant can we use cycle detect algo which we use when in case of undirected graph for this problem too.

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Both should work.

  • @binay_krishn
    @binay_krishn Před 3 lety

    how can we approach the same problem by the use of topo sort.???

  • @adithya61
    @adithya61 Před rokem

    whats the time complexity?

  • @punjabicodingstyle5111
    @punjabicodingstyle5111 Před 4 lety +1

    First viewer and first comment

  • @As-zr3bu
    @As-zr3bu Před 3 lety

    not able to understand the code of line 9. What are we trying to check?

  • @nagashayanr5940
    @nagashayanr5940 Před 4 lety +1

    Can we call this backtracking algorithm? because graph coloring adjacent nodes made more sense in Possible Bipartition problem. In this its backtracking and you are calling it coloring graph right?

    • @techdose4u
      @techdose4u  Před 4 lety

      Recursion in general is called backtracking. It is also using coloring concept due to maintaining 3 states like colors. But I said similar to graph Coloring and not exactly graph Coloring.

    • @nagashayanr5940
      @nagashayanr5940 Před 4 lety

      ​@@techdose4u oh ok, got it. thanks :)

  • @lampyclampy
    @lampyclampy Před 4 lety +1

    Sir , plz start videos on weekly leetcode contest solutions

  • @muskankushwah2639
    @muskankushwah2639 Před 3 lety

    Sir please tell me why we go for graph coloring way as its directed we could do by simple visited array. Im confusing why we switch this to find cycle in directed graph sir please rply !?

  • @tanyashreeatul9591
    @tanyashreeatul9591 Před 4 lety +1

    Hello Sir, can you please tell me what can go wrong if we use only a boolean visited array instead of processing and processed options ?

    • @techdose4u
      @techdose4u  Před 4 lety +1

      It will take N2 time. It will run. You need to maintain the states of the already processed elements. So, you need one more vector. Better to use just one integer vector maintaining all 3 state info.

  • @shubhayandas379
    @shubhayandas379 Před 4 lety +1

    can we use union find algorithm to detect cycle?

  • @Yash-uk8ib
    @Yash-uk8ib Před 4 lety +1

    linked lists can also be used i believe... plzz correct me if I am wrong.

    • @techdose4u
      @techdose4u  Před 4 lety +1

      If you use linked list then it should be an array of linked list to form your adjacency list. It will be cumbersome and so go with array.

    • @Yash-uk8ib
      @Yash-uk8ib Před 4 lety

      @@techdose4u okk thanks

  • @prarthitmehra9108
    @prarthitmehra9108 Před 4 lety +1

    Can this algorithm be coded in iterative way i.e. without recursion?

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Apply BFS for iterative approach.

  • @spetsnaz_2
    @spetsnaz_2 Před 3 lety

    Code Link : techdose.co.in/course-schedule-deadlock-detection-graph-coloring/

  • @brandonfong9998
    @brandonfong9998 Před 3 lety

    i'm a little confused, it looks to me like the directed graph is the same as the input to me. could anyone help clarify why the directed graph is needed?

    • @gaganb
      @gaganb Před 3 lety

      Had the same question, did you figure out why? I thought the "prerequisites" was already an adjacency list.

    • @gaganb
      @gaganb Před 3 lety

      Oh, now I realize, the input is actually always a "pair" with only two numbers each. Example, [[1,0],[0,1]]. This is neither an adjacency list nor an adjacency matrix.

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

    And If there is no deadlock,if they ask you sequence of courses Topological Sorting will be the answer

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

      Yea but they dint ask that. Simply they asked if it was possible to take all courses. So cycle detection is sufficient. In toposort, we will start processing with indegree 0 and hence order will be perfect but cycle detection can start anywhere. But order is not important here. So cycle detection is enough.

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

      @@techdose4u Yeah thats why I mentioned "If"

  • @syedkaja2045
    @syedkaja2045 Před 3 lety

    can we calculate the frequencies of each element and frequency of any element is greater than 2 return false else true
    will this work?

    • @shreshthsingh7744
      @shreshthsingh7744 Před 3 lety

      No beacuse same node can point more than one node. Otherwise we could also use the linked list to solve this problem.

    • @E__ShameemahamedS-bx2ed
      @E__ShameemahamedS-bx2ed Před 3 lety

      @@shreshthsingh7744 oh okay thanks bro

  • @divyanshuchaudhari5416

    bhai,,,arrows ulte rahenge na

  • @xunianzu
    @xunianzu Před 3 lety

    If the code runs concurrently, will there be data race on the visited array?

    • @ayokunlesunmola60
      @ayokunlesunmola60 Před 3 lety

      The code can’t exactly run concurrently , unless if you use separate machines or something

  • @AnkushKumar-mk8ns
    @AnkushKumar-mk8ns Před 3 lety

    THIS CODE IS TO FIND CYCLE IN DIRECTED GRAPH
    can someone help to find the mistake in this code.
    I use unordered map here to make a adjcency list
    and visited is also taken as unordered_map.
    template
    class Graph{
    public:
    unordered_map adjList;
    void addEdge(T u, T v, bool biDir=true){
    adjList[u].push_back(v);
    if(biDir){
    adjList[v].push_back(u);
    }
    }
    void Print(){
    for(auto node : adjList){
    cout

  • @bhaskar08
    @bhaskar08 Před 4 lety +1

    This is illegal, you can't post a solution today.

    • @techdose4u
      @techdose4u  Před 4 lety +5

      This is not a contest but just a casual challenge with solutions flooded all over the internet and in discussions as well. What do you want to point at? If someone wants help, they can get the entire code and explanation and also I never post videos of any live contest. So what's the deal?

  • @jonathandimuccio91
    @jonathandimuccio91 Před 3 lety

    what a banger

  • @sarfrazkhan2261
    @sarfrazkhan2261 Před 4 lety +1

    Bro, why your insta is private :P

    • @techdose4u
      @techdose4u  Před 4 lety

      Should it be public? I don't have any experience in insta 😅

    • @sarfrazkhan2261
      @sarfrazkhan2261 Před 4 lety +3

      @@techdose4u if you are sharing link here, it should be public, you are celebrity 😁

    • @techdose4u
      @techdose4u  Před 4 lety +3

      😅 Made it public now