Linked List Cycle - MUST KNOW: Floyd's Tortoise and Hare Algorithm

preview_player
Показать описание
Linked List Cycle - MUST KNOW: Floyd's Tortoise and Hare Algorithm

Common computer science interview question asked by Google, Facebook, Amazon, etc..

Song: LAKEY INSPIRED - Chill Day (Vlog No Copyright Music)
Music provided by Vlog No Copyright Music.

Other Interview Questions:
Рекомендации по теме
Комментарии
Автор

nice, brief explaining exactly what I wanted instead of a confusing 30-plus min lecture. Thank you.

Sami
Автор

If you want to build upon this to return a index value of loop start, you need to do a couple of things:

1. fast can not be initialized to head.next, but needs to be set to head, same as slow

2. the guard clause "if not head" needs to be changed to "if not head and or not head.next"

3. and of course, now that slow and fast starts at the same node, "while slow != fast:" will never be true. So you need to change that clause. One way is to use a flag like this:

flag = False
while slow != fast or flag is False:
flag = True


I'm a newbie coder so I might be wrong, but without these changes I would get infinite loops and attribute errors.

scullyy
Автор

On second 49' you mentioned using a hashset. Unless you are certain that the linkedlist only contains nodes with unique values otherwise having duplicates won't define a cycle.

stevenmugishamizero
Автор

Detail, the algorithm doesn’t check wether the first value of fast is null or not.

sourandbitter
Автор

Great Explanation, But One change is needed from the python code. While Checking Fast.next and fast.next.next it is also good to check fast alone also so that the code passes test condition with just one node. My Solution:- if not head:
return False

slow = head
fast = head.next

while slow != fast:
if not fast or not fast.next or not fast.next.next:
return False
slow = slow.next
fast = fast.next.next

return True

mathesh
Автор

Hi there, I hope someone can help me answer this simple question.

From the code in the video, I understand that 'fast' is already 1 node ahead of 'slow' (given 'fast' = head.next while 'slow' is only slow = head). And down below, it's fast = fast.next.next (2 more nodes ahead). Then, shouldn't fast be 3 nodes ahead of slow instead of 2 like Derek said?
Thanks heaps!

abidvu
Автор

Your function raises AttributeError on list of 1 node.

kbgagt
Автор

what if the linked list has duplicate values, does it still work?

TheRuthlessEAZY
Автор

Neat trick -- not very useful to me, but neat trick I suppose.

BlackJar
Автор

You don't find the connecting point of the cycle this way (they don't necessarily meet at it in the first iteration), for finding the start of the cycle there's a second step in the algorithm where you walk with one pointer from the start, and with one pointer from the found intersection, both one point at a time, and return where they meet. This works because

user