Given the
Output: true
Explanation: There is a cycle; the tail connects back to node with value 2.
Output: true
Explanation: The tail connects back to the head.
Output: false
Explanation: There is no cycle in the list.
Floyd's cycle detection algorithm uses two pointers moving at different speeds. If a cycle exists, the fast pointer will eventually lap the slow pointer and they will meet inside the cycle. If no cycle exists, the fast pointer reaches the end of the list.
- Initialize two pointers:
slow andfast , both starting athead . - In each iteration, move
slow one step forward andfast two steps forward. - If
fast orfast.next becomesnull , the list has no cycle — returnfalse . - If
slow == fast , the two pointers have met inside a cycle — returntrue .
Complexity Analysis:
Time complexity: O(n) where n is the number of nodes. In the worst case (no cycle), fast pointer traverses all nodes. With a cycle, the two pointers meet after at most n iterations.
Space complexity: O(1) as only two pointers are used regardless of list size.