Linked List Cycle
Given the headnexttruefalse
Example 1
Output: true
Explanation: There is a cycle; the tail connects back to node with value 2.
Example 2
Output: true
Explanation: The tail connects back to the head.
Example 3
Output: false
Explanation: There is no cycle in the list.
Solution Approach - Floyd's Tortoise and Hare
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:
andslow , both starting atfast .head - In each iteration, move
one step forward andslow two steps forward.fast - If
orfast becomesfast.next , the list has no cycle: returnnull .false - If
, the two pointers have met inside a cycle: returnslow == fast .true
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class LinkedListCycle {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // move 1 step
fast = fast.next.next; // move 2 steps
if (slow == fast) {
return true; // cycle detected
}
}
return false; // fast reached end, no cycle
}
}
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.