15% off all plans & roadmaps Use code

See plans

Linked List Cycle

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^5
  • pos is -1 or 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 head can be null. Every pointer access must be guarded.
  • pos is 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create an empty set seen that will hold node references.
  2. Set node = head.
  3. While node is not null, check whether node is already in seen.
  4. If it is, return true, because you have returned to an earlier node.
  5. Otherwise add node to seen and move to node.next.
  6. 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

TimeO(n)
SpaceO(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 False
Fast & Slow (Cycle Detection) pattern infographic for Linked List Cycle

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

  1. If the list is empty the loop below never runs, so the answer is false.
  2. Set both slow and fast to head.
  3. Loop while fast is not null and fast.next is not null, so that two steps are safe.
  4. Move slow one node: slow = slow.next.
  5. Move fast two nodes: fast = fast.next.next.
  6. After moving, compare the two references. If slow == fast, return true.
  7. If the loop exits, fast reached 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.

RoundGuard (fast, fast.next non-null)slow after movefast after moveEqual?
startn/aA (3)A (3)not checked
1A and B exist: yesB (2)C (0)no
2C and D exist: yesC (0)B (2), via D then Bno
3B and C exist: yesD (-4)D (-4), via C then Dyes, 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

TimeO(n)
SpaceO(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 False

Common mistakes

  • Writing fast = fast.next.next with a loop guard of only while fast. On an odd-length straight list, fast.next is null at the last node and the next access crashes. Guard with while 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 fast in Python, == on references elsewhere).
  • Putting the slow == fast check before the first move, when both pointers still sit on head. 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.val in 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 (head is null): return false. The loop never runs and nothing is dereferenced.
  • Single node with pos = -1: return false. Fast has no next, so the loop exits at once.
  • Single node whose next points 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 head and 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

Practise it