What is the fast and slow pointers pattern for linked lists?
LeetCode Patterns Flashcards: Linked List, Fast and Slow Pointers, Reversal, Cycle
Аудио-карточка · 0:30Nortren·
What is the fast and slow pointers pattern for linked lists?
0:30
The fast and slow pointers pattern, also called Floyd's tortoise and hare, uses two pointers moving at different speeds through a linked list. The slow pointer moves one node at a time while the fast pointer moves two nodes. If a cycle exists, the fast pointer will eventually catch the slow pointer inside the cycle. If no cycle exists, the fast pointer reaches the end. Beyond cycle detection, this pattern finds the middle of a linked list because when the fast pointer reaches the end, the slow pointer is exactly at the middle. This runs in O of n time and O of one space.
neetcode.io