MemotivaLeetCode Patterns Flashcards: Linked List, Fast and Slow Pointers, Reversal, Cycle

How do you detect a cycle in a linked list?

LeetCode Patterns Flashcards: Linked List, Fast and Slow Pointers, Reversal, Cycle

Аудио-карточка · 0:28

Nortren·

How do you detect a cycle in a linked list?

0:28

Use Floyd's cycle detection: start both slow and fast pointers at the head. Move slow one step and fast two steps at each iteration. If fast reaches a null pointer, there is no cycle. If slow and fast meet, a cycle exists. To find where the cycle begins, reset one pointer to the head and keep the other at the meeting point. Move both one step at a time. The point where they meet again is the cycle start. This works because the distance from the head to the cycle start equals the distance from the meeting point to the cycle start going around the cycle.
neetcode.io