Linked List Cycle (LeetCode 141): Solution and Explanation

Easy
Hash Table
Linked List
Two Pointers

Given the head of a singly linked list, determine whether following next pointers ever brings you back to a node you already visited, which means the list contains a cycle instead of ending at null.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The straightforward approach remembers every node you pass. Walk the list, and before moving on, check whether the current node is already in a hash set. If it is, you have looped back and there is a cycle; if you reach None, there is not. That runs in O(n) time but needs O(n) memory, and the usual follow-up asks for constant space.

Floyd's cycle detection, often called the tortoise and the hare, gets rid of the set. Send two pointers from the head: slow moves one node per step and fast moves two. If the list has an end, fast reaches it first and you can stop with false. If there is a cycle, both pointers eventually enter it and keep running around it forever, so the question becomes whether they are guaranteed to land on the same node.

They are. Once both are inside the loop, look at the gap from fast forward to slow. Each step, slow moves forward one and fast moves forward two, so fast closes the gap by exactly one node. A gap that shrinks by one every step cannot jump over zero; it must hit zero, at which point the two pointers are on the same node. Because the gap is at most the cycle length, they meet within one lap of slow after it enters the cycle, which keeps the total work linear.

Approach: Floyd's fast and slow pointers

  1. Start both slow and fast at head.
  2. Loop while fast and fast.next are not None, so the double step is always safe.
  3. Move slow one node forward and fast two nodes forward.
  4. If slow == fast (the same node object), a cycle exists, so return True.
  5. If the loop exits because fast reached the end, the list terminates, so return False.

Step-by-step example

head = [3, 2, 0, -4], pos = 1 (the tail -4 links back to the node 2)
  1. Start: slow = 3, fast = 3.
  2. Step 1: slow moves to 2. fast moves 3 → 2 → 0, landing on 0. They differ.
  3. Step 2: slow moves to 0. fast moves 0 → -4 → 2, landing on 2. They differ.
  4. Step 3: slow moves to -4. fast moves 2 → 0 → -4, landing on -4. slow and fast are the same node, so return True.

Code: Python, Java, C++

1class Solution:
2    def hasCycle(self, head: Optional[ListNode]) -> bool:
3        slow, fast = head, head
4        
5        while fast and fast.next:
6            slow = slow.next
7            fast = fast.next.next
8            if slow == fast:
9                return True
10        return False

Time and space complexity

Time

O(n)

Without a cycle, fast reaches the end after about n/2 steps. With a cycle, slow needs at most n steps to enter it and at most one more lap for fast to catch up, so the total stays linear.

Space

O(1)

Only the two pointer variables are used, regardless of the list length.

Other approaches

Hash set of visited nodes (time O(n), space O(n))

Store each node reference in a set and report a cycle when a node repeats. It is simple and also tells you the first repeated node, but it uses memory proportional to the list length.

Mark visited nodes in place (time O(n), space O(1))

Overwrite each visited node's value or pointer with a sentinel and detect the sentinel when it reappears. It uses no extra memory but destroys the list, which is usually unacceptable.

Common mistakes

  • Checking only fast in the loop condition and then reading fast.next.next. If fast.next is None, that access crashes; the condition must test both fast and fast.next.
  • Comparing node values instead of node identity. Two distinct nodes can hold the same value without any cycle.
  • Comparing the pointers before moving them. Since both start at head, they are equal at the start, and the function would always return true.
  • Storing values rather than node references in the hash set variant, which reports false cycles whenever a value repeats.

Frequently asked questions

Why do the fast and slow pointers always meet in a cycle?

Inside the cycle, the fast pointer gains exactly one node on the slow pointer per step. The gap between them shrinks by one each time, so it must reach zero rather than skip past it.

Can you detect a cycle in a linked list without extra space?

Yes. Floyd's algorithm uses just two pointers, so its extra space is O(1), while still running in O(n) time.

Why does the fast pointer move two steps and not three?

With a speed difference of one, the gap closes by exactly one each step and can never be skipped. Larger speeds also work eventually, but two keeps the reasoning and the null checks simplest.

How do I find where the cycle starts?

After the pointers meet, move one of them back to the head and advance both one step at a time. The node where they meet again is the start of the cycle.