15% off all plans & roadmaps Use code
See plansLinked List Cycle
- LeetCode 141
- Easy
- Two Pointers
- Fast & Slow (Cycle Detection)
Updated
TL;DR: Decide whether following `next` pointers from `head` ever loops back. Move one pointer one step and another two steps per turn. They meet inside a cycle, or the fast one falls off the end.
Problem
You are given head, the head of a singly linked list. Determine whether the list contains a cycle.
A cycle exists if some node can be reached again by following next pointers. Internally, pos is the index of the node that the tail's next pointer connects to, or -1 if the tail points to nothing. pos is not passed to your function.
Return true if the list has a cycle. Otherwise, return false.
Example 1
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: The tail connects back to the node at index 1 (0-indexed).
Example 2
Input: head = [1,2], pos = 0 Output: true Explanation: The tail connects back to the node at index 0.
Example 3
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the list.
Constraints
- The number of nodes in the list is in the range
[0, 10^4]. -10^5 <= Node.val <= 10^5posis-1or a valid index in the list.
Constraints that matter
- Up to 10^4 nodes means even an O(n^2) re-walk (about 5 * 10^7 comparisons) is borderline in slow languages. Linear time is the target.
- The list may be empty (0 nodes), so
headcan be null. Every pointer access must be guarded. posis hidden from you. You cannot index into the list or use it, so you must detect the loop from pointer behavior alone.- Node values can repeat and can be negative. Values say nothing about identity, so you must compare node references, never
val. - The follow-up asks for constant memory. That rules out storing visited nodes and points to two pointers moving at different speeds.
Hints
Hint 1
This is the fast and slow pointers pattern, also called Floyd's tortoise and hare.
Hint 2
Walk the list from the head.
Solution
Intuition
This is the fast and slow pointers pattern, also called Floyd's tortoise and hare. The question is whether a walk along next pointers ever ends. A list without a cycle ends at null. A list with a cycle never does.
Picture the two pointers as runners on a loop track, with fast moving twice as quickly as slow. The faster runner laps the slower one, the way fast meets slow inside the cycle, while on a straight road the faster runner finishes first.
You cannot walk until you reach null, because in a cycle you never do. You need a way to recognize that you have been somewhere before. You can remember every node (a hash set), or you can use two walkers whose relative motion exposes the loop.
Send a slow walker one step at a time and a fast walker two steps at a time. If the list is straight, the fast walker reaches null first and you answer false. If there is a cycle, both walkers eventually end up inside it, and the fast one starts closing in on the slow one.
The gap between them shrinks by exactly one node per round, because fast gains 2 and slow gains 1. A gap that shrinks by one each round cannot jump over zero. So the fast walker lands on the slow walker, and equal references prove a cycle. This uses two pointers and no extra memory.
Worked example
Input: head = [3, 2, 0, -4], pos = 1 Output: true Explanation: The list is 3 -> 2 -> 0 -> -4, and the tail (-4) points back to the node holding 2. Walking forward from the head never reaches null. It goes 3, 2, 0, -4, 2, 0, -4 and keeps looping, so the answer is true.
Approach 1: Brute force: remember every visited node
Walk the list from the head. Before stepping onto a node, ask whether you have stepped onto it already. If yes, the walk is looping, so return true. If you reach null, the list ended, so return false.
You need a fast way to answer "have I seen this node?". A hash set of node references answers it in O(1) on average. The set must hold the node objects themselves, not their values, because two different nodes can hold the same value.
Steps
- Create an empty set
seenthat will hold node references. - Set
node = head. - While
nodeis not null, check whethernodeis already inseen. - If it is, return true, because you have returned to an earlier node.
- Otherwise add
nodetoseenand move tonode.next. - When the loop ends, you hit null, so return false.
Dry run
Name the nodes A (3), B (2), C (0), D (-4). D.next points to B.
- Visit A. Not in the set, so add it. Set: {A}.
- Visit B. Not in the set, so add it. Set: {A, B}.
- Visit C. Add it. Set: {A, B, C}.
- Visit D. Add it. Set: {A, B, C, D}.
- Step to D.next, which is B. B is already in the set, so return
true.
The answer matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. Each node is added to the set at most once, because the walk stops the first time it meets a node already in the set. So the loop runs at most n + 1 times and each iteration does O(1) average work. The set can hold all n nodes before the repeat is found, so extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
seen = set()
node = head
while node:
if node in seen: # same node object seen before: loop
return True
seen.add(node)
node = node.next
return FalseJavaTested in our runner
import java.util.*;
class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<>();
ListNode node = head;
while (node != null) {
// add returns false when the node is already present
if (!seen.add(node)) {
return true;
}
node = node.next;
}
return false;
}
}C++Tested in our runner
#include <unordered_set>
class Solution {
public:
bool hasCycle(ListNode* head) {
std::unordered_set<ListNode*> seen;
ListNode* node = head;
while (node != nullptr) {
if (seen.count(node)) {
return true;
}
seen.insert(node);
node = node->next;
}
return false;
}
};JavaScriptTested in our runner
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
const seen = new Set();
let node = head;
while (node !== null) {
if (seen.has(node)) {
return true;
}
seen.add(node);
node = node.next;
}
return false;
};GoTested in our runner
func hasCycle(head *ListNode) bool {
seen := make(map[*ListNode]bool)
node := head
for node != nil {
if seen[node] {
return true
}
seen[node] = true
node = node.Next
}
return false
}C#Tested in our runner
public class Solution {
public bool hasCycle(ListNode head) {
var seen = new HashSet<ListNode>();
ListNode node = head;
while (node != null) {
// Add returns false when the node is already present
if (!seen.Add(node)) {
return true;
}
node = node.next;
}
return false;
}
}
Solution pattern
Fast & Slow (Cycle Detection)
Part of Two Pointers
Approach 2: Fast and slow pointersOptimalFast & Slow (Cycle Detection)
What's slow: the hash set spends O(n) memory to remember the whole path, when you only need to know that the path loops. The follow-up asks for constant memory, so the set has to go.
The insight that fixes it: two pointers moving at different speeds act as their own memory. Slow moves one node per round and fast moves two. In a straight list, fast reaches null. In a cycle, fast catches slow from behind, because the gap between them shrinks by one each round and must hit zero.
Steps
- If the list is empty the loop below never runs, so the answer is false.
- Set both
slowandfasttohead. - Loop while
fastis not null andfast.nextis not null, so that two steps are safe. - Move
slowone node:slow = slow.next. - Move
fasttwo nodes:fast = fast.next.next. - After moving, compare the two references. If
slow == fast, return true. - If the loop exits,
fastreached the end of the list, so return false.
Dry run
Nodes: A (3), B (2), C (0), D (-4), with D.next = B. Both pointers start at A. The table shows the state after each round.
| Round | Guard (fast, fast.next non-null) | slow after move | fast after move | Equal? |
|---|---|---|---|---|
| start | n/a | A (3) | A (3) | not checked |
| 1 | A and B exist: yes | B (2) | C (0) | no |
| 2 | C and D exist: yes | C (0) | B (2), via D then B | no |
| 3 | B and C exist: yes | D (-4) | D (-4), via C then D | yes, return true |
In round 2, fast moves from C to D and then follows D.next back to B. In round 3, slow steps from C to D, and fast moves from B to C to D. Both sit on D, so the function returns true, which is the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the number of nodes. With no cycle, fast moves two nodes per round and hits null after at most n / 2 rounds. With a cycle, let a be the nodes before the cycle and L the cycle length, so a + L = n. Slow enters the cycle after a rounds, and at that moment fast is already inside, with the gap from slow to fast less than L. The gap drops by one per round, so they meet within L - 1 more rounds, for at most a + L = n rounds in total. Only two pointers are stored, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
# fast and fast.next must both exist before moving two steps
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # compare identity, not values
return True
return FalseJavaTested in our runner
import java.util.*;
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// fast and fast.next must both exist before moving two steps
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}C++Tested in our runner
class Solution {
public:
bool hasCycle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
// fast and fast->next must both exist before moving two steps
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
};JavaScriptTested in our runner
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
let slow = head;
let fast = head;
// fast and fast.next must both exist before moving two steps
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
};GoTested in our runner
func hasCycle(head *ListNode) bool {
slow, fast := head, head
// fast and fast.Next must both exist before moving two steps
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
return true
}
}
return false
}C#Tested in our runner
public class Solution {
public bool hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// fast and fast.next must both exist before moving two steps
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}Common mistakes
- Writing
fast = fast.next.nextwith a loop guard of onlywhile fast. On an odd-length straight list,fast.nextis null at the last node and the next access crashes. Guard withwhile fast and fast.next. - Comparing
slow.val == fast.val. Two different nodes can hold the same value, so a list like[1, 1, 1]with no cycle would wrongly return true. Compare node references (slow is fastin Python,==on references elsewhere). - Putting the
slow == fastcheck before the first move, when both pointers still sit onhead. They are equal immediately, so every non-empty list returns true. Move first, then compare. - Checking only
head.next == head. That catches a single-node self-loop but misses a cycle such as 1 -> 2 -> 3 -> 2. The cycle can start anywhere and have any length. - Storing
node.valin the hash set instead of the node. Duplicate values then look like a revisit and give false positives. Store the node object itself. - Moving fast by three steps while slow moves one. The gap now shrinks by two per round, so if the gap is odd and the cycle length is even, fast hops over slow forever. Use speeds that differ by exactly one: 1 and 2.
Edge cases
- Empty list (
headis null): return false. The loop never runs and nothing is dereferenced. - Single node with
pos = -1: return false. Fast has nonext, so the loop exits at once. - Single node whose
nextpoints to itself (pos = 0): return true. After one round both pointers are on that node. - Two nodes
[1, 2]with the tail pointing to the head: return true. Slow and fast meet after one or two rounds. - Duplicate values with no cycle, such as
[1, 1, 1]: return false. Only reference equality counts. - A straight list of 10^4 nodes: return false after about 5000 rounds with no recursion, so there is no stack risk.
Follow-ups interviewers ask
- Can you solve it in O(1) extra memory?
- Yes, that is the fast and slow pointer solution. It keeps two node references and nothing else, so space is O(1) while time stays O(n). The hash set version needs O(n) memory because it stores every visited node.
- How do you find the node where the cycle begins?
- Run Floyd's algorithm until slow and fast meet. Then reset one pointer to
headand move both one step at a time. They meet at the cycle's first node. The distance from head to the cycle start equals the distance from the meeting point to the cycle start, modulo the cycle length. This is Linked List Cycle II. - How do you find the length of the cycle?
- After slow and fast meet, keep one pointer fixed and walk the other forward one node at a time, counting steps until it returns to the fixed node. That count is the cycle length. It takes at most L extra steps, so the total stays O(n) time and O(1) space.
Linked List Cycle FAQ
What is the time complexity of Linked List Cycle?
Both standard solutions run in O(n), where n is the number of nodes. The hash set visits each node once. Fast and slow pointers finish within n rounds, because slow needs a rounds to enter the cycle and fast closes the gap within one more lap, at most a + L = n.
Why use fast and slow pointers for Linked List Cycle?
They detect a loop without remembering visited nodes. Fast moves two steps and slow moves one, so inside a cycle the gap shrinks by exactly one per round. A gap that shrinks by one cannot skip past zero, so the pointers must meet. Without a cycle, fast reaches null.
Can Linked List Cycle be solved in O(1) extra space?
Yes. Floyd's tortoise and hare uses only the slow and fast references. You cannot do better than O(1), and you do not need to give up O(n) time to get it.
Why can the fast pointer not jump over the slow pointer?
Inside the cycle, fast gains exactly one node on slow per round. If the gap is k, the next gap is k - 1, then k - 2, and so on down to 0. Every gap value is visited in order, so fast lands on slow.
Why compare nodes and not values in Linked List Cycle in Python or Java?
A cycle is about the same node appearing again, not the same number. Different nodes can share a value, so a value comparison gives false positives. In Python, is makes the identity check explicit. ListNode does not define a custom equality, so == also falls back to identity there, but is states the intent.
Do I need the pos parameter to solve LeetCode 141?
No. pos only describes how the test list was built, and your function never receives it. You detect the cycle purely by following next pointers.
Asked at
See which companies ask this — Pro
Related problems
- Contains Duplicate · same technique: Fast & Slow (Cycle Detection)
- Happy Number · same technique: Fast & Slow (Cycle Detection)
- Contains Duplicate II · same technique: Fast & Slow (Cycle Detection)
- Sort Colors · next harder, same pattern
- Two Sum · same pattern: Two Pointers
- Valid Anagram · same pattern: Two Pointers
- Plus One · same pattern: Two Pointers
- Missing Number · same pattern: Two Pointers
- Remove Duplicates from Sorted Array · same pattern: Two Pointers
- Remove Element · same pattern: Two Pointers