A Two Pointer algorithm, moving through a list sequence at different speeds. It uses two pointers one moving twice as fast as the other one. The faster one is called the fast pointer and the other one is called the slow pointer.
When to use
- Find a loop in a linked list.
- Find middle node in a linked list.
- Find starting node of a loop in a linked list.
Mechanism
Finding Middle Node
- Traverse the list
- Move slow pointer one step at a time
- Move fast pointer two steps at a time
- When the fast pointer hits the end of the list, the slow pointer is at the middle
Finding Cycles
While traversing the linked list one of these things will occur
- The Fast pointer may reach the end
null
which shows that there is no loop in the linked list. - The Fast pointer again catches the slow pointer at some time therefore a loop exists in the linked list.
- Traverse the list
- Move slow pointer one step at a time
- Move fast pointer moves two steps at a time.
- If there’s a cycle, the fast pointer will eventually catch up with the slow pointer within the cycle because it’s moving faster.
- If there’s no cycle, the fast pointer will reach the end of the list (i.e., it will become null).
- When the slow and fast pointers meet, a cycle or loop exists.
Finding First Node of a Cycle
- Same as normal cycle detection
- After detecting that the loop is present
- Reset slow pointer to head
- Keep fast pointer at its position
- Both slow and fast pointers move one step at a time
- When fast equals slow, slow will be the starting node of loop.