ไม่สามารถเล่นวิดีโอนี้
ขออภัยในความไม่สะดวก

Course Schedule - Graph Adjacency List - Leetcode 207

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ส.ค. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    Twitter: / neetcode1
    Discord: / discord
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    Problem Link: neetcode.io/problems/course-s...
    0:00 - Read the problem
    1:40 - Drawing Solution
    10:50 - Coding solution
    leetcode 207
    This question was identified as a Google interview question from here: github.com/xizhengszhang/Leet...
    #leetcode #graph #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

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

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

    🚀 neetcode.io/ - A better way to prepare for Coding Interviews

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

      think of a directed graph 0->1->2->3->4, isn't your solution's time complexity O(E * N**2)...you will start the same loop for 1, 2, 3, 4 after doing it for 0

  • @xmnemonic
    @xmnemonic ปีที่แล้ว +171

    The .remove(crs) was so confusing but I finally understood it. Simplest explanation: if we exit the for-loop inside dfs, we know that crs is a good node without cycles. However, if it remained in the visited set, we could trip the first if-clause in the dfs function if we revisit it and return False. That's what we don't want to do, because we just calculated that crs has no cycles. So we remove it from visited so that other paths can successfully revisit it.
    Basically we can visit the node twice without it being a cycle due to it terminating multiple paths.

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

      and the reason it terminates at 'twice' is because of preMap[crs] = []

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

      thank you! i was pulling out my hair trying to figure out why

    • @wayne4591
      @wayne4591 ปีที่แล้ว +19

      Actually you can see this trick in many graph, binary tree or other problems using back tracking. Because the visit set is only used to contain the current visit path. So whenever you exit the sub-function you create on this level, you have to pop the info you passed in before.

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

      in every dfs, pop() or remove() after a call, is a standard process. you will see.

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

      Do you have any example?

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

    The setting of preMap[crs]=[] before return true is so smart!!! Absolutely love it

    • @yuemingpang3161
      @yuemingpang3161 2 ปีที่แล้ว +17

      Pretty smart! He removes all pre-courses at once after iterate through one adjacency list. In the drawing solution, he removes the pre-courses one by one. To align with the codes, the list can only be "cleaned out" if all pre-courses returns true. Actually, I was a little bit confused when I first saw the codes.

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

      @@yuemingpang3161 what is the time and space complexity of this solution??

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

      And necessary for time complexity to be O(num_nodes). If we didn't do it, the last for loop would have us visiting nodes as many times as it required by other courses, making the overall complexity O(n^2).

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

      It's too smart

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

      not only smart, but essential for a good running time.. hell I fell there!!!

  • @saralee548
    @saralee548 2 ปีที่แล้ว +43

    Your channel is soo helpful! If I get stuck on a LC question I always search for your channel! Helped me pass OAs for several companies. Thank you so much.

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg 2 ปีที่แล้ว +1

    Great explanation, I was doing the adj list pre->course and confused myself in the coding step. Thanks for the video, smart ideas. I definitely was not thinking of the fully connected graph case

  • @eliasl7705
    @eliasl7705 2 ปีที่แล้ว +6

    Thank you so much for all of these videos. Very well explained and also well put together and displayed. Really fantastic material, it's been absolutely invaluable in helping me to learn and improve my skills.

  • @idgafa
    @idgafa 11 หลายเดือนก่อน +20

    If you move the line 13 `if preMap[crs] == []` before the line 11 `if` check, then you don't need the `visitedSet.remove(crs)` in line 19, because you will never traverse the visited path that way. Thanks for great explanation.

    • @Alex-tm5hr
      @Alex-tm5hr 28 วันที่ผ่านมา +1

      You can actually just remove it all together and it still passes lol

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

    Thank you so much pal! I was able to crack it myself after seeing your visualizations of the graph, with ease. Words can't describe my happiness.

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

      what is the time and space complexity of this solution??

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

    Thank you! Great explanation! And you have a magical voice, such a pleasure to listen to your explanations.

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

    this is a clever solution. not something i would ever come up with haha, i had a similar idea, but it kind of just broke down during the dfs step. i had a lot of trouble trying to figure out how to detect cycles in a directed graph...in the end when i was looking in the discussion i saw that you could just do a topological sort so i felt silly after that haha. gotta work on graph problems more :-)

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

      what is the time and space complexity of this solution??

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

      @@alfahimbin7161 O(n + p) where n is the number of courses and p the prerequisites. The explain it at around 08:37

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

    He is speaking the language of god.🔥🔥

  • @sanaa3151
    @sanaa3151 2 ปีที่แล้ว +18

    this was so so helpful, thank you so much for being so clear!

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

      Glad it's helpful!

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

    What a lucid explanation! Keep this up!

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

      what is the time and space complexity of this solution??

  • @chenyu-jg4kg
    @chenyu-jg4kg 6 หลายเดือนก่อน

    Brilliant Solution!! It took me a while to think it through but finally understood it, really appreciate your help!

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

    clear solution, thank you! Wish you could also go over BFS 😄

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

    SO clear! Thanks a lot

  • @MP-ny3ep
    @MP-ny3ep ปีที่แล้ว

    Phenomenal explanation! Thank you so much!

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

    I meet this question today, thank you so much.

  • @farleylai1102
    @farleylai1102 2 ปีที่แล้ว +8

    LintCode imposes the memory constraint such that recursive DFS will fail.
    The intended solution should be iterative based topological sort.

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

    Hey man, thanks a lot for your description. You probably have the best explanation on this this problem compared to other TH-camrs. There’s a girl that’s pretty good too her names jenny

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

    I have taken Neetcode's Course Schedule 2 idea and implemented this on those lines:
    Personally I found that idea more intuitive and easier to follow.
    class Solution {
    HashMap prereq = new HashMap();
    // hashset to mark the visited elements in a path
    HashSet completed = new HashSet();
    // we use a hashset for current path as it enables quicker lookup
    // we could use the output to see if the node is already a part of output,
    // but the lookup on a list is O(n)
    HashSet currPath = new HashSet();
    public boolean canFinish(int numCourses, int[][] prerequisites) {
    // base case
    if (numCourses

  • @N.I.C.K-
    @N.I.C.K- ปีที่แล้ว

    Thank you!!! Such a great teacher

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

    Very nice. Thanks for making this

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

    thanks for the n = 5 expample, cleared the ques for me !

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

    Killer explanation. Thank you.

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

    Your explanation is super clear, thanks

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

      what is the time and space complexity of this solution??

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

    Forgot the remove part. You are amazing

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

    You explanaition is amazing, I love it !

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

      Glad it's helpful!

  • @fazliddinfayziev-qg1vg
    @fazliddinfayziev-qg1vg 9 หลายเดือนก่อน

    So amazing brother. Thank you

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

    I implemented DFS via a stack. I also tried a similar approach with BFS using a deque queue but it was a lot slower.
    class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
    graph = defaultdict(list)
    for prereq in prerequisites:
    graph[prereq[0]].append(prereq[1])
    for i in range(numCourses):
    if i in graph:
    stack = graph[i]
    seen = set()
    while stack:
    node = stack.pop()
    if node == i:
    return False
    if node not in seen:
    for j in graph[node]:
    stack.append(j)
    seen.add(node)
    return True

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

    Awesome solution!

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

    Intuitively I was thinking of this solution and gave myself 30 mins to solve it, I got to the part of DFS but then confused myself because I was like "I feel like I need DFS here but where should I start it, how should I call it" and then the time was up xD, I'm happy I almost came up with it alone though. Thanks for the video, it clarified what I was having trouble with.

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

    Bro, you are just GOLD!

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

    Thank you so much!

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

    Thank you for this awesome video! I am wondering if you could do a video about a BFS version of the same problem? Thank you very much!

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

    I literally looked at this question yesterday and couldn’t get it, thanks for making this vid!

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

      A nice coincidence! Thanks for watching

  • @Allen-tu9eu
    @Allen-tu9eu 2 ปีที่แล้ว +3

    you are the very best one for explain leetcode problems, and I am not even a python user

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

      Thanks! =)

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

    To simplify this problem
    This is based on finding if the directed graph has a cycle. If yes then return false(cannot complete all courses) else return true.

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

      I feel the way the problem is worded, I never realized that it was asking this question lol

  • @JuanGonzalez-cl2fy
    @JuanGonzalez-cl2fy 3 ปีที่แล้ว

    Thanks for this wonderful video!

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

    You are legend man!!!

  • @namelesslamp12
    @namelesslamp12 3 ปีที่แล้ว

    looking sharp thanks

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

    Brilliant explanation, wow.

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

    When I did this exercise for the first time, I actually created a whole complete graph data structure from scratch.
    Then created 2 visited maps to resolve the circular issue. So much memory required

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

    Wow... The best explaination... ❤️

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

    Thanks for your explanation! it is clean and easy to percept. I really appreciate your coding style.
    Just a heads up that the if perMap[crs] == [] return True can be omitted since if we have an empty array for prerequisites for crs, the for loop afterwards will just end and return True at the end!

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

      Yes, though, you save "some time" by handling it that way.

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

    @NeetCode Thank you so much for your work! I'am going through collection of your solutions and litterally feeling smarter)
    I don't really understand one thing in this problem - why do they provide numCourses at all? I mean, when given number is less then total number of courses provided in prerequisites - like (1, [[0, 1]]) the algorithm fails. And of course you dont realy need this number to create preMap (you could use defaultdict, or check if key exists on string 14 before comparing to empty list). Iteration through length of preMap also will work when running dfs.

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

    If you want to take course 1, you have to take course 0 first.

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

    I have a hard time envisioning visited.remove(crs). I cannot connect this to the "Drawing Solution" earlier. I can see when preMap[crs] is set to 0 @7:44, but I cannot see any part where visisted.remove(crs) corresponds to.
    I understand to detect a cycle, we need to visisted.add(crs), But I cannot see where visited.remove(crs) fits.
    Can someone help?

    • @RanjuRao
      @RanjuRao 3 ปีที่แล้ว

      Lets say course 3 is dependent on 2 and 2 is on 1, while traversing for 3 you make dfs(2) which in turn is dfs(1) but dfs(1) does not have pre-req so u mark it as [] (initially) and similarly you need to mark dfs(2) to [] which is done using set.remove() and map.append([] ) for key =2 .

    • @akinfemi
      @akinfemi 3 ปีที่แล้ว

      Same. What helped me was thinking about it as setting the course node to a "leaf node". If you notice the leaf nodes (courses with no prerequisites) are never added to the visited set. So setting it to [] and removing it from the set does that.

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

      I think it makes more sense if you replace visitSet.remove() with visitSet.clear(). visitSet.clear() also works for our purpose, which is basically to give us a new visitSet for each course so we don't get false positives from earlier runs.

    • @jessepinkman566
      @jessepinkman566 2 ปีที่แล้ว +10

      When the graph is not fully connected. 1->2->3, 4->3. If you should not remove 3, 4->3 would be false because 3 is already in the set. However, you can also choose to change the order of the two ifs in the start of the bfs to avoid removing.

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

      feel the same thing.

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

    good explanation on dfs, thanks! and i like the name of your channel :)

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

      Happy it's helpful :)

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

    I tackled this problem as cycle detection.

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

    Love your videos! Would love to see the code included as well, especially in Javascript as converting can be tough. Thanks NeetCode :)

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

    I was really confused about the direction of the edges. Intuitively, I would think precourse -> course, but you have the arrows going backwards from course -> precourse. By switching the arrows around to: precourse -> course, and having your adjacency list as: { precourse: [ course ] } instead of: { course: [ precourse ] }, your DFS solution still works. The benefit to doing it this way is that you can use the same adjacency list pattern for a BFS topological sort approach, which needs access to the neighbors of nodes with zero in-degrees.

  • @yumindev
    @yumindev 2 ปีที่แล้ว +5

    in the example case [1,0], why is it out reach arrow 1-> 0 ? I thought in order to get 1, you need to get 0 first, so, it's 0->1 ? am i right? it's a little anti-intuitive ?

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

    I feel using Kahn's algorithm for detecting cycles in the directed graph is the simplest solution for this, even though logically not 100% right as we use indegree in Kahn's algorithm, as soon as I see cycle and undirected graph I solved it with this method.
    Then I got to know we are supposed to deal with outdegree to deal with independent nodes in this case!
    Though Kahn's algo works !

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

    we dont need to travese 4 from 1 if we are keeping track of the visited nodes. cross edge iterations can be eliminated to increase the speed of the algorithm, right?

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

    Thank you neetcode guy

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

    Could you also go through the space complexity in your videos?

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

      Given N = number of courses, P = prerequisites; TC: O(N + P), because we are visiting each "node" once, and each "edge" once as well. SC: O(N+P), as our hashmap is of size N + P, and the recursive call stack + visited set are of size N.

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

    without the empty list optimization this will get TLE, pretty smart to figure that out

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

    Thanks Neetcode!
    Is this playlist supposed to be followed sequentially?
    Thanks

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

    Great explanation. I understood it so clear . Awesome work..

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

    Thanks for the very clear explanation. I have a suggestion for direction of arrows that may be less confusing. For example, prerequisites = [[1,0]] means that if we have to take course 0 before course 1. So my graph would be pictured like: 0------->1 instead of 1------>0.

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

      Depends on how we see it. In his case, the concept is like 1 has a dependency on 0, hence drew an edge from 1 pointing towards 0.

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

      Yeah that was so confusing

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

    This was good!

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

    you dont need to remove crs from visited at the end if you just check adj==[crs] before checking crs in visitSet

    • @user-j5ja95
      @user-j5ja95 10 หลายเดือนก่อน

      huh ?

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

    Explanation on WHY/HOW cycle was detected(The crux of the problem)
    -As we perform dfs, we add node to 'visited' set if it does not exist.
    -Once we have exhausted all its neighbors/prerequisites AND return back to it from call stack, we pop it from call stack
    and we remove from 'visited' set.
    -A cycle is detected when the node we are popping off of call stack still exists in 'visited' set.
    BUT WHY??
    In the last example he provides @ 10:50, while we have/are visiting the last neighbor/prepreq of node 0, unfortunately we have
    not returned back to it due to its order in call stack. Hence a cycle was detected before we we're able to remove node 0 from call stack.

  • @Rahul-pr1zr
    @Rahul-pr1zr 2 ปีที่แล้ว +4

    Nice explanation. Curious - why/how did you zero in on using DFS instead of BFS?

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

      @rahul, to check if a particular course completion can be possible. And we can do it if and only if we can check all its prerequisite.

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

    why do we have to remove the crs from the visited set at line 19? what is the purpose?

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

    this question is currently being asked at Amazon. My brother is one of the interviewers who asks it hehe

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

    I don’t quite understand. Is it about topological sort or some other kind of algorythm? Like finding cycles for example

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

    this channel is great

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

    Dude this literally SAVED me!

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

    Great video. I wonder if you could solve this problem with a tortoise & hare algorithm?

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

    Quick question: I was trying to solve this using the Ailen Dictionary method you also made a video of. I can't get it to pass all test cases. May I ask if the method for the alien dictionary can be applied to this one?

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

    I came up with the same idea but didn't know how to code. How should I improve?

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

    Smart solution ✨

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

    What is the space complexity ? Since we are using HashMap and Set?

  • @JoffreyB
    @JoffreyB 2 ปีที่แล้ว +12

    You draw edge incorrectly. If it's [0, 1] meaning you first have to take course 1 before 0, edge is gonna be 1->0, not 0->1, because first we need to take 1 and only then we will have access to the 0.

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

      his solution models the graph in the other direction, it is still correct because he is consistent with it

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

      I was thinking the same thing, the arrows threw me off

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

      The arrows/wording is messed up, he’s using the word prerequisite to actually mean postrequisite, but good video still

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

      yeah all his arrows are backwards I don't know how that makes sense to him.

  • @user-ik4ju3vs2z
    @user-ik4ju3vs2z 10 หลายเดือนก่อน

    This is very clear explanation, but I met Time Limit Exceeded problem, so I made the follow changes to met the requirements:
    class Solution(object):
    def canFinish(self, numCourses, prerequisites):
    """
    :type numCourses: int
    :type prerequisites: List[List[int]]
    :rtype: bool
    """
    adjacency_list = [[] for _ in range(numCourses)]
    for crs, prec in prerequisites:
    adjacency_list[crs].append(prec)

    visited = [0] * numCourses
    def dfs(crs):
    if visited[crs] == 1:
    return False
    if visited[crs] == 2:
    return True
    visited[crs] = 1
    for prec in adjacency_list[crs]:
    if not dfs(prec):
    return False
    visited[crs] = 2
    return True
    for crs in range(numCourses):
    if not dfs(crs):
    return False
    return True

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

    @NeetCode Can you please explain the time complexity in detail.

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

    how come you don't use a set instead of a list for the visitedSet? One would need to use the nonlocal keyword but the lookup times are much quicker. Couldn't there be an edge case where your last node in the dfs loops back to the second to last and then you are searching the whole array. This could potentially happen a couple times no? Thanks for any clarity you can provide!

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

    I don’t really get what
    If not dfs(pre):
    Return false
    Is doing. I understand it’s checking if the statement is false but what is it doing specifically?

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

    Not able to do the BFS solution of this problem, got stuck in thinking how it will be approached, tried with one problem getting TLE in 29th test case.
    Can anyone help!

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

    In the beginning you show the edge going the wrong way for [1,0] the direction of the arrow should be from 0 to 1

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

    Simplest and easiest explanation. Thankyou!

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

    Hello everyone, this is YOUR daily dose of leetcode solutions

  • @mr.probable1236
    @mr.probable1236 11 หลายเดือนก่อน

    thanks

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

    Why can't your map be an integer as the key and an integer as the value? Why does the value have to be a list? I thought it would be okay to declare the map as int, int since you have one prereq for each course

  • @rohit-ld6fc
    @rohit-ld6fc 2 ปีที่แล้ว +1

    so isnt it just a detect cycle problem? if cycle exists return false else true ?

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

    I think you have it backwards around 1:19 but no big deal. 1 is a prereq of 0

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

    I have to say if you didn't realize this was a graph problem or to just think about it literally initially about courses and prerequisites you can get pretty stuck with where to go. :(

  • @dcc5244
    @dcc5244 5 หลายเดือนก่อน +1

    The more you learn about recursion, the more crazy you become.

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

    can someone tell me why are we removing elements from visitSet? Thanks

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

    its been almost three months i am doing leetcode but still cannot come up with my own solution, can anybody tell me exactly what is thats wrong i am doing? :(

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

    much clear than leetcode sol

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

    I am not understanding why we set preMap[crs] = [], in the drawing solution we just removed one by one after checking. Why are we just removing all the prereqs after one is checked?

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

      the for loop will remove all its neighbors first

  • @edwardteach2
    @edwardteach2 3 ปีที่แล้ว

    U a God

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

    Is this considered topological sort?

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

    Viewed this solution after an hour of trying to solve it and yep like usual there's no way my dumbass self could come up with this on my own

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

    Can someone please explain why the time complexity of this is V+E. I cant understand for the life of me. Thanks

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

    you can use a defaultdict(list) instead for preMap :)

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

    Lines 13 and 14 are redundant. if preMap[crs] == [], code will skip the for loop and return True at L 21 already