Linked List Cycle II
Given the headnull
Example 1
Output: Node with value 2
Explanation: The cycle starts at node index 1 (value = 2). The tail connects to this node.
Example 2
Output: Node with value 1
Explanation: The tail connects back to the head; the cycle start is the head node.
Example 3
Output: null
Explanation: No cycle in the list.
Solution Approach - Floyd's Cycle Detection
This is a two-phase algorithm based on Floyd's Tortoise and Hare:
Phase 1 - Detect the cycle: Move slowfast
Phase 2 - Find the cycle start: After the meeting point is found, reset one pointer to head
Why does Phase 2 work? Let FCaF + aF + a + n*C2(F+a) = F+a+nCF = nC - aFF
- Use fast and slow pointers to find the meeting point inside the cycle.
- If fast reaches null, return null (no cycle).
- Reset one pointer to head; advance both one step at a time until they meet.
- The meeting point is the cycle start node.
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// Phase 1: detect if cycle exists
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// Phase 2: find cycle start
ListNode pointer = head;
while (pointer != slow) {
pointer = pointer.next;
slow = slow.next;
}
return pointer; // cycle start node
}
}
return null; // no cycle
}
}
Complexity Analysis:
Time complexity: O(n) where n is the number of nodes. Both phases together traverse the list a constant number of times.
Space complexity: O(1) as only two pointers are maintained.