Back to All Questions
Linked List Cycle Detection
Google
Linked List
Two Pointers
Given the head of a linked list, determine if the linked list has a cycle in it.
A cycle exists if some node in the list can be reached again by continuously following the next pointer. Return true if there is a cycle, false otherwise.
Solution Walkthrough
This is the classic "tortoise and hare" problem, solved elegantly with Floyd's Cycle Detection Algorithm using two pointers moving at different speeds.
- Initialize a
slowpointer and afastpointer, both starting athead. - On each step, move
slowforward by one node andfastforward by two nodes. - If the list has no cycle,
fast(orfast.next) will eventually hitnull— returnfalse. - If the list does have a cycle,
fastwill eventually "lap"slowand they will point to the same node — returntrue.
Because the gap between the two pointers shrinks by one node every step once both are inside the cycle, they are guaranteed to meet. This runs in O(n) time with O(1) extra space — no visited-set required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Related Algorithms