The Fast & Slow pointer approach, also known as the Hare & Tortoise algorithm, is a pointer algorithm that uses two pointers which move through the array (or sequence/LinkedList) at different speeds. This approach is quite useful when dealing with cyclic LinkedLists or arrays.
By moving at different speeds (say, in a cyclic LinkedList), the algorithm proves that the two pointers are bound to meet. The fast pointer should catch the slow pointer once both the pointers are in a cyclic loop.
var slow = head;
var fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // pointers met
return true;
}
}
If we need to find cycle node, we can take head and slow(cycle pointer) and iterate till they meet, cause the gap between them has cycle size.
var slow = head;
var fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
var slow2 = head;
while (slow2 != slow) {
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
Usually we're looking for O(N)
time and O(1)
space.
How does Floyd's slow and fast pointers approach work? - GeeksforGeeks