Given the head of a linked list, determine if the linked list has a cycle in it. A cycle exists if there is some node in the list that can be reached again by continuously following the next pointer. Return true if there is a cycle, false otherwise.
head = [3,2,0,-4], pos = 1truehead = [1,2], pos = 0truehead = [1], pos = -1falseslow = head, fast = headfast != null && fast.next != nullslow = slow.next (+1 step)fast = fast.next.next (+2 steps)slow == fast → cycle detected, return truereturn falseIf a cycle exists, fast enters the loop first. From that point, every iteration reduces the gap between slow and fast by 1 (fast gains 2, slow gains 1 → net gain 1 per iteration). The gap starts at most L (loop length), so they meet within L additional iterations — O(n) total.
If no cycle, fast will reach a null node (or a node whose .next is null) within O(n/2) steps.
Storing every visited node in a hash set works, but uses O(n) space. Two pointers can do it with O(1) space.
Move a slow pointer one step and a fast pointer two steps at a time. If there is no cycle, fast reaches null. If there is a cycle, fast laps around and meets slow.
Floyd's tortoise and hare. A faster runner on a circular track always catches the slower one.
Run the animation above on your own input, or watch the 1:11 video explanation of Linked List Cycle with a dry run and Java code.