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.

  1. Initialize a slow pointer and a fast pointer, both starting at head.
  2. On each step, move slow forward by one node and fast forward by two nodes.
  3. If the list has no cycle, fast (or fast.next) will eventually hit null — return false.
  4. If the list does have a cycle, fast will eventually "lap" slow and they will point to the same node — return true.

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