Skip to content

visual walkthrough

Linked List Cycle

EasyFast & Slow PointersReported at: AmazonMicrosoftGoogle+4

Floyd's cycle detection in its simplest form.

Solve on LeetCode

The idea

Without a cycle, walking the list eventually hits null. With one, the walk goes round forever, so you need a way to notice.

Send two pointers, one twice as fast. If there's a loop, the fast one laps the slow one and they meet; if not, the fast one hits the end.

Complexity

approachtimespace
Remember every nodeO(n)O(n)
Slow and fast pointersO(n)O(1)

More walkthroughs