💡 LINKED LIST PLAYLIST: kzbin.info/www/bejne/fWHCemCQe5WGaZo
@algorithmo1343 жыл бұрын
@NeetCode can you solve binary tree cameras a dp question next? TQ
@joelbisponegrao99322 жыл бұрын
This guy is insane, he is helping a whole bunch of people getting new jobs and understanding algo than anyone ever. He deserves the best.
@misterimpulsism2 жыл бұрын
I've seen Floyd's Tortoise & Hare algorithm many times and have taken it for granted. This is by far the best explanation of why it works and why it's O(n) time. Many thanks to Neetcode!
@gayan17422 жыл бұрын
Explaining how it always evaluates to O(n) is really helpful.
@licokr8 ай бұрын
It's crazy. To undderstand Floyd's Tortoise and Hare, I watched a lot of videos on KZbin but it couldn't work and I gave up. Today, I was solving Leetcode 141 problem and to find a solution with space O(1), I watched it and wow... There were already lots of times 'WOW' while watching neetcode' videos, but wow... 10-(2-1), n-1.. this guy got me understand this. just with two lines. Crazy. I learn a lot from your videos, not only algorithm...
@juliuscecilia60053 жыл бұрын
hands down best leetcode youtuber
@sanjanar91982 жыл бұрын
Please keep posting solutions like this, they are really helpful
@seanmcelroy4074 Жыл бұрын
Thanks, explaining the slow pointer increases the distance by 1 and the fast pointer decreases distance by 2 shows how the distance is always decreasing by 1 so fast will never overtake!
@NeetCode Жыл бұрын
Thank you so much!
@moewiseman1557 Жыл бұрын
unless it overtake by surpassing the slow pointer in this case it might take more than 1 cycle right?
@ruzaikr11 ай бұрын
The explanation of the Floyd's Tortoise and Hare algorithm was amazing!
@rioredwards Жыл бұрын
Great solution! I found one that is simpler, although might be considered the "easy way out".... If you set each node's value to None/null/undefined (depending on the language), then you can just check for if the current node is undefined in the loop. This solution is slightly faster than the slow/fast pointer method: class Solution(object): def hasCycle(self, head): if not head: return False while head.next: if head.val == None: return True head.val = None head = head.next return False
@Jesseiceheart Жыл бұрын
Great solution: 1. Altering source linked list is not idael in a real time scenario, unless the arg passed is already a deep copy of the original linked list and not just a shallow copy. 2. If we had to create a deep copy ourselves, it'll add up to the memory utilised by our solution.
@louisuchihatm25564 ай бұрын
@@Jesseiceheart In C/cpp, by specifying const to the list passed, the function will return with an unaltered list. Is there a way to do this in python? bool hasCycle(const head){}
@abhisekdash28642 ай бұрын
That 10 + (1-2) example really did it. Thanks bro
@stormarrow21202 жыл бұрын
to be technical, when you store an object like a Node in a dictionary in python we are storing the address in the dictionary/set. That is how we can be sure that we have not seen it before using the "hashset" approach. Felt it was worth commenting. BTW saw your video the other day about you working in Seattle at Google! well deserved. I love your content! You may look into becoming a CS teacher when you're burnt out working at major tech giants. haha keep them coming!
@osmanmusse94322 жыл бұрын
Thanks for telling us
@cadenc.7368 Жыл бұрын
Thank you! I was wondering how the objects were being stored in the hashset since the node objects themselves are not hashable, but now I see that their memory addresses are.
@sujal1548 Жыл бұрын
when you are doing the comparison of fast == slow, what exactly is happening? Are the memory addresses being compared in that way as well? If so, what is the difference between the comparison x == 5 where x is 5 and fast == slow? How does Python know to compare memory addresses for fast and slow and actual values for x == 5?
@sujal1548 Жыл бұрын
chatgpt answer to my question, let me know if it's correct: In Python, the comparison x == 5 is different. It compares the value of the variable x (which is 5) with the value 5. Python knows that x is an integer, so it compares the integer value directly. However, when it comes to objects in Python, such as the ListNode instances in the linked list, the comparison slow == fast compares the memory addresses of the objects. It checks whether slow and fast are referring to the same object in memory, rather than comparing the contents of the objects.
@BudetSvobodnoy10 ай бұрын
@@sujal1548 good question, I'd love to know how it works in JavaScript as well. Not sure if we should trust gpt on this one
@Andres-dn8ze7 ай бұрын
@neetcode is goated! I was having a hard time with some of the previous linked list questions in neetcode 150 but with this one I was able to solve it first by using a hashSet and then did the follow up once I saw someone mention tortoise and hare's algo because i assumed it had to mean slow and fast pointers if memory complexity was O(1). I feel like with a lot of the leetcode questions you keep getting beat up until eventually some of the topics 'click' and then you finally start seeing the fruits of your labor! Thanks neetcode you're the man 🙏
@adewumisunkanmi55932 жыл бұрын
Honestly, this is a technique anyone should not miss..it just makes the whole problem easy to solve.Thanks NeetCode
@TenzDelek8 ай бұрын
every time brings a whole new concept to learn. grateful for that
@McBritish2 жыл бұрын
Always love your videos. I've been working hard on LC problems for the last 10 days and I always come to these videos when I get stuck or would love to learn a clean, concise solution.
@omarllama2 ай бұрын
Here is another easy but O(1) memory solution with only one pointer. We can take advantage of the fact that: (-10**5
@gwtuts4061 Жыл бұрын
Sigma solution - print function in python : # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: if head is not None: # print(head.next) will automatically tell if it has # cycle or not. so use it to get answer... # it prints as Error - Linked list has cycle a = str(head.next) if a[0] == "E": return True return False
@SiddharthRanjan61977 ай бұрын
@NeetCode a more intuitive way to understand this by taking a real world example i.e., an analog clock. The seconds hand moves faster than the rest but because all hands move in a circle...they are bound to converge at certain point in time.
@_ipsissimus_3 жыл бұрын
"Given Head" lmao these leetcode prompts are juicy
@tomonkysinatree5 ай бұрын
Great explanation, I feel like the coding portion really avoided some odd edge cases and made it seem simpler than it is. For example, we started the pointers at the same point and then updated the pointers first instead of at the end of the loop.
@taco5642 жыл бұрын
Amazing explanation on why it's linear time! Thank you!!
@emmanueltemiede6197 Жыл бұрын
best explanation for the Tortoise and hare algorithm i have seen so far, thanks
@bandhammanikanta2 жыл бұрын
Thank you for solving the problem with first brute force and then with the optimised solution.
@devin3944 Жыл бұрын
Fantastic visualization as to why the 2 offset pointers work
@ankitdubey50455 ай бұрын
Those who have studied relative motion can easily understand it,taking slow to rest then the fast will meet the slow that is at rest
@daniyalkhawaja19133 ай бұрын
I used an in-place replacement method. I believe this passes the O(1) argument and seems more efficient, but this approach seems better if we have to maintain the original input list (which is probably desired in most applications anyway).
@pedroalonsoms Жыл бұрын
excellent explanation on why slow and fast eventually meet each other
@juliramoos10 ай бұрын
I loooove the way you explain things. Make them so much easier
@rajeshseptember092 жыл бұрын
perfectly articulated explanation. Thanks much ! I could only think of a hashMap solution - but the hare and tortoise pointer approach is much more efficient.
@adarshsasidharan254 Жыл бұрын
hands down the best explanation/proof of the Floyd's Cycle Detection Algorithm
@nirupamsuraj1634 Жыл бұрын
Those who know physics just imagine this in terms of relative velocity( i know this sounds wierd 😅 but trust me). So the fast pointer have a velocity of 2 and slow have a velocity of 1. Now imagine you are sitting on the slow pointer. Then the fast pointer is travelling at a relative speed 2-1 = 1. So if it is a cycle, the fast pointer will move at a speed 1 and eventually collides you. If it is not a cycle the fast pointer just moves away from you at a speed 1. Let me know if you find this usefull
@sabba2_10 ай бұрын
With the first approach you can simply edit node values to something unique, so if you encounter your unique value again it means you detected a cycle. O(n) time O(1) space.
@altusszawlowski420911 ай бұрын
Great explanation! Although since the problem doesnt state that we are not allowed to manipulate the linked list, we can just change all the vals to None as we see them and check if the val is None to determine a cycle. This obviously wouldnt work if the input had nodes with vals of None though.
@wlcheng3 жыл бұрын
Brilliant solution! Thank you for creating this video!
@bianchialex2 жыл бұрын
I didnt understand this algorithm for legit a year until today. Thank you.
@CodingWithPrakash_2 жыл бұрын
Best explanation for why floyd algo works
@JustinK09 ай бұрын
i just used a map to save the nodes address as a string, so if node.next's address is already in the map its a cycle, not as fast as this but its still O(n), just uses more memory
@osmanmusse94322 жыл бұрын
Wow that was great explanation you just did, I really appreciate it neetcode for what your doing I know you work also it can be hard making these sort of videos with great visual solution.
@ashkan.arabim4 ай бұрын
respects to the insane creative brain that came up with this AND TO YOU for presenting it in such an awesome way!!
@nghiavo62632 жыл бұрын
You blowed my mind with fast and slow pointer technique
@The6thProgrammer Жыл бұрын
Since there were no rules against modifying the original linked list, my approach was to actually move through the linked list and reverse the list as I traversed it. I only had to store a single node in a hash map (the original head) so the memory complexity was O(1). Once you move through a cycle all the nodes you encounter after the cycle are now reversed so the path will take you back to the original head and you can return true if you find a match against the single node in the hash map, otherwise false if you encounter NULL.
@evgeniyazarov4230 Жыл бұрын
Did the same, yet you don't need a hashmap to store the list's head, just save a pointer to it
@The6thProgrammer Жыл бұрын
@@evgeniyazarov4230 good point!
@chrischika7026Ай бұрын
you shouldnt unless stated otherwise
@sahilkassanjee8022 жыл бұрын
Great explanation. I wasn't understanding the second method, but you explained it perfectly
@80kg3 жыл бұрын
Thank god this is such an amazing explanation!!! AS ALWAYS!!!
@alpyldrm8448 Жыл бұрын
I have managed to solve it with a hash map but this is a much elegant solution. Thanks for the video.
@natekrall20156 ай бұрын
here's an O(1) runtime solution. Problem said there's a max of 10000 nodes, so... def hasCycle(self, head: Optional[ListNode]) -> bool: #edge case [] if not head: return False curr = head for i in range(10001): if not curr: return False curr = curr.next return True O(10001) = O(1)
@yinglll74113 жыл бұрын
Thank you man, as soon as you mentioned two pointers it just clicked for me. Thank you!
@saurabhkathar23742 жыл бұрын
Great Explanation, you are the best teacher for coding solutions🙏🙏
@vimalalwaysrocks Жыл бұрын
This is not Leetcode, this is "Neet" code. Excellent! Would have loved it if you could have also added how to find the node of the loop start which is what 142. Linked List Cycle II is asking us to find.
@pranjalnama24202 жыл бұрын
amazing explanations sir, did not understand this algo before but you made it pretty easy
@musicgotmelike96682 жыл бұрын
Something about your pronounciation just makes me understand the topics;) Keep up the great work!
@UKMatt322 жыл бұрын
I’m not sure if my solution is best practice but instead of using hashing I just set the value of visited nodes to be a value outside of their specified range. Then, if node.next’s value was equal to this “visited” value, there was a cycle. If it doesn’t reach any visited nodes there is no cycle and it returns false. My submission was faster than 96% and better memory than 98% roughly
@gradientO Жыл бұрын
Best explanation of why runner catches up with walker!
@itstheguy172 жыл бұрын
Very clear and detailed explanation, thanks a lot!
@noobletify8693 жыл бұрын
An explanation I can actually understand 😅 Thanks!!
@Emorinken2 ай бұрын
You’re the real MVP man! Thanks
@chaiben2754 ай бұрын
The intuition for this algo is literally so simple. Imagine you're running on track with a friend who always runs faster than you. Eventually, you'll always find your friend catching up to you from behind if the track is a circle
@Skadongle2 ай бұрын
I think its not that simple since most people get caught on the idea of “what if the fast one jumps over the slow one without hitting the slow node” but about 2 seconds of thinking should be enough to get past that so idk why he spent so long on the intuition part of this vid
@regnam5032 ай бұрын
I just pointed the "next" of all the visited nodes to my dummy node. As soon as I hit the one that has a "next" of my dummy, I know that's a cycle.
@NeilSharma-u5n2 ай бұрын
clever
@akermiyu2 жыл бұрын
Why do we moved the fast pointer by 2 instead of another number? Does moving the slow pointer by 1 and the fast pointer by 2 always ensure that we can catch a cycle if there is one?
@MacAndSwiss2 жыл бұрын
Nice video! The proof was super helpful.
@wilsonwang86412 жыл бұрын
The most valuable part to me starts from 8:20.
@TransparentWorld1275 Жыл бұрын
You mentioned at the beginning of the video that you already completed a problem already similar to this - which video/topic is that? The "Finding a duplicate number" video?
@EduarteBDO Жыл бұрын
if slow is increasing by 1 and fast by 2 that means the gap between the two is decreasing by 1, so it's guarantee that the gap will reach in n time because the biggest possible gap is n the length of the list
@pjchen8605 Жыл бұрын
Super helpful and amazing explanation! Thanks so much!
@效应多普勒 Жыл бұрын
Cystal clear explanation, thanks a lot!
@alextech48812 жыл бұрын
Eureka effect on steroids. Thanks so much for posting these, they really help A LOT!
@Relqeds2 жыл бұрын
Awesome....I like the way you explain ...very clean and easy way...pls keep posting ..thank you!!
@hemesh56633 жыл бұрын
Hands down best youtube channel.
@divyam1175Ай бұрын
Oh thanks that really help a lot 8:06
@symbol7672 жыл бұрын
Thanks man just wanted to see how you coded it out, you the man! Liked
@adityachache2 жыл бұрын
I did this and the second version of this where we have to return the node by using hash table
@ianokay Жыл бұрын
No one on their own will ever think that the best way to do that is to presume the pointers collide, that's absolutely insane reasoning for an "Easy" problem. Couldn't you just have 2 pointers one ahead of the other, and if the ahead pointer is ever behind the behind pointer (by checking the `pos` which they claim is a node attribute index value) then it's a loop? That seems much more intuitive and sane use of two pointers, but I see how this insane theory-based one is the only solution for not having some comparable index value (but then I mean, could you not cast the nodes to an array and just make an index value anyways?)
@ManojKumar-if1jh2 жыл бұрын
There is a problem if you use hashset because, we will have to override the hashcode method for the ListNode custom class which is created.
@mfaani Жыл бұрын
If slow goes 1 Fast goes 2 And slow goes first… And the whole cycle is n steps, then once fast gets ahead i.e. after its first step, then think of more as slow is already on its next lap. How many iterations does fast have to take? To match slow? n - delta Delta is 2 - 1 So if it was 10 steps it would be 10 - ( 2 - 1) If you actually think of fast getting ahead then fast well is always ahead. He purposely didn’t use ahead but said gap. But depending on how you think of it, it can be vague a bit…
@chunkwanchan5503 Жыл бұрын
if fast & slow start at different node, and the fast pointer move 3 or 4 or 5 times faster than the slow pointer. I found that in some cycle structure, the two pointers will never meet, why is that? Thanks in advance.
@Bhaskar58902 жыл бұрын
Hey....... you have great teaching skills... please create a separate array and string playlist....... also which s/w you use for drawing explanations.
@mohamedantar1249Ай бұрын
Best explanation on the planet
@kaydeeinmy10 ай бұрын
omgg, Neetcode you're the legendary !!!!!
@NivAwesome16 күн бұрын
I have a very easy solution, O(1) space complexity without slow and fast pointers: var hasCycle = function(head) { while (head) { if (head.val === (10 ** 5) + 1) { return true; } head.val = (10 ** 5) + 1; head = head.next; } return false; };
@Ahmad_Al-Deeb7 ай бұрын
Thanks a lot. I would appreciate if you can tell me the tool you are using for drawing.
@sriramkrishnamurthy44732 жыл бұрын
NOW THAT IS WHAT IS AN INTUITIVE EXPLANATION ❤🙏🙏👍
@binup282 жыл бұрын
Great explanation! Thank you. Could you kindly do a similar awesome explanation for leetcode 142 Linked List Cycle II ?
@kirillzlobin7135 Жыл бұрын
This explanation is sooooooooooooooooooooooooooooooooo ammmmmmmmmmmmmmmmmmmmmaaaaaaaaaaaaazing. Thank you very much!!!
@ikthedarchowdhury89472 жыл бұрын
Can't we use Valid palindrome solution here? Like using Two pointers but in polar opposite nodes/ pointers? Then checking if l = r?
@joeljerry1494 Жыл бұрын
Would there ever be a situation where the fast pointer always overshoot the short pointer so that they will never meet?
@akshaibaruah17203 жыл бұрын
i never really comment on ytb videos but this was so well explained that I simply have to commend you for this great explanation!!
@BradleyWeston9211 ай бұрын
Any idea on cleaning up a looped linked list? I ended up double free'ing on the loop.
@jackchen52883 жыл бұрын
Thanks for all the explanations!
@samwilson45972 жыл бұрын
this man is the GOAT
@kmeenakshi26792 жыл бұрын
Next level explanation Dude..!! Just loved it :D
@RutvikPatel26113 жыл бұрын
line 12, in hasCycle while fast and fast.next: AttributeError: 'list' object has no attribute 'next'
@flatmapper11 ай бұрын
Amazing explanations
@furkan4867 ай бұрын
Clean explanation
@AliHassan-ec9nu Жыл бұрын
thansk for such an awesome explanation.
@samrobinson-isaiah-53v52 жыл бұрын
I see that the solution uses a .next is anyone else having trouble getting the .next to work? I tried next(next(fast)) but that doesn't work because the first next converts the type from list to integer. I have also converted the input list: head = iter([3,2,0,-4)]
@helikopter12312 жыл бұрын
i also would like to know
@azatnurzhanuly72902 жыл бұрын
That was a great video tutorial about the topic, thank you!!!!
@Kazeys3 ай бұрын
lol this was one of my exams and I blanked. Thanks
@jamesmee7201 Жыл бұрын
The while loop executes if fast.next is not None. Why doesnt an error get throwing when we assigned fast to fast.next.next assuming fast.next.next is eventually going to hit None in a non Cycle list