An interactive visualization of Floyd's cycle detection algorithm (tortoise and hare). Watch how two pointers moving at different speeds can detect whether a linked list contains a cycle.
Linked List LeetCode 141 โ Easyhead, the head of a linked list, determine if the linked list has a cycle in it.next pointer.
Internally, pos is used to denote the index of the node that tail's next pointer is connected to.
Note that pos is not passed as a parameter.true if there is a cycle in the linked list. Otherwise, return false.
fun hasCycle(head: ListNode?): Boolean { var slow = head var fast = head while (fast != null && fast.next != null) { slow = slow?.next fast = fast.next?.next if (slow == fast) { return true } } return false}
Floyd's cycle detection uses two pointers moving at different speeds: a slow pointer (tortoise) that moves one step at a time, and a fast pointer (hare) that moves two steps at a time.
If there is a cycle, the fast pointer will eventually lap the slow pointer and they will meet inside the cycle.
If there is no cycle, the fast pointer will reach the end of the list (null).
slow and fast start at headslow forward 1 node, move fast forward 2 nodesfast is not null and fast.next is not nullTruefast reached the end of the list โ no cycle, return False
If there is no cycle, the fast pointer reaches the end in n/2 steps.
If there is a cycle, the fast pointer closes the gap by 1 node per iteration, so they meet within one full loop of the cycle.
Only two pointer variables are used โ no extra data structures needed.