Description
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
Thinking Process
- Using two pointers, we can determine if there is a cycle in the list
- When the two pointers meet, the fast pointer will travel 1 more cycle than the slower pointer.
- Assume the cycle begins at position A, and slow pointer is at position A + B when the two pointers meet
- The fast pointer would have travelled 2(A+B) distance when the pointers meet, which means that the cycle length is (A+B)
- Hence after travelling another A step, the slow pointer will reach the head of the cycle
Code
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode n1 = head;
ListNode n2 = head;
while(n1 != null && n2 != null){
n1 = n1.next;
n2 = (n2.next != null) ? n2.next.next : null;
if(n1 == n2 && n1 != null){
while(n1 != head){
n1 = n1.next;
head = head.next;
}
return head;
}
}
return null;
}
}
Complexity
- Space complexity is O(1)
- Time complexity is O(n)