ToolMight Logo
EasyLinked ListTwo PointersFast and Slow PointersFloyd's Tortoise and Hare

Linked List Cycle

Detect whether a linked list loops back on itself. Compare O(n)-space node-identity tracking against Floyd's O(1)-space fast-and-slow pointer algorithm.

Optimal Time
O(n)
Optimal Space
O(1)
Primary Pattern
Fast and Slow Pointers
Visualizer
Open Interactive View →

Problem Statement

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Examples & Constraints

Example 1
Input: head = [3, 2, 0, -4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail links back to the 1st node (index 1, val 2).
Example 2
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints
  • The number of the 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 linked-list.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Cycle detection or midpoint discovery in singly linked lists with O(1) extra memory almost always uses two pointers advancing at 1x and 2x speeds.

Core Invariant

Once both slow (+1/step) and fast (+2/step) occupy a loop of circumference C, the distance between them narrows by exactly 1 node every step so fast never skips past slow.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Visited Node Reference Hash Set
O(n)O(n)Traverse the list once while recording each node's pointer/object identity in a Hash Set; a repeated pointer proves a cycle exists.
2. Floyd's Tortoise and Hare (Fast & Slow Pointers)Optimal
O(n)O(1)Advance a slow pointer by 1 step and a fast pointer by 2 steps. If a loop exists, the fast runner is guaranteed to lap and intersect the slow runner.

1. Visited Node Reference Hash Set

TimeO(n)
SpaceO(n)

Traverse the list once while recording each node's pointer/object identity in a Hash Set; a repeated pointer proves a cycle exists.

Time ComplexityO(n)

Visits each node at most once with O(1) average hash-set lookups.

Space ComplexityO(n)

Stores up to N node pointers in the hash set.

How It Works

Recording Previously Seen Memory Addresses

The most direct test for revisiting a node is storing every visited node reference (NOT its integer .val) inside a visited set:

  1. Start at curr = head.
  2. While curr != null:
  • If curr already exists in visited, return true.
  • Add curr to visited and advance curr = curr.next.
  1. Reaching null confirms there is no cycle (return false).

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Visit Nodes 3, 2, 0, -4

Insert distinct node references for 3, 2, 0, and -4 sequentially into visited.

State:visited size = 4
Strengths
  • +Minimal mental overhead
  • +Naturally exposes the exact entry node of the cycle on first revisit
Trade-offs
  • -Allocates O(n) extra memory
  • -Hash collisions/overhead slower than raw two-pointer traversal

Reference Implementation

Complete implementation for Visited Node Reference Hash Set in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def has_cycle_set(head) -> bool:
visited = set()
curr = head
while curr:
if curr in visited:
return True
visited.add(curr)
curr = curr.next
return False

2. Floyd's Tortoise and Hare (Fast & Slow Pointers)

Optimal
TimeO(n)
SpaceO(1)

Advance a slow pointer by 1 step and a fast pointer by 2 steps. If a loop exists, the fast runner is guaranteed to lap and intersect the slow runner.

Time ComplexityO(n)

If there is no cycle, fast reaches the end in N/2 iterations. If there is a cycle, slow enters the cycle after K steps and fast catches up in at most C steps. Total steps <= N.

Space ComplexityO(1)

Only two pointer references (slow and fast) are maintained throughout execution.

How It Works

The Mathematical Intuition: Closing the Gap

Imagine two runners on a circular running track. If Runner A runs at 1 meter/second and Runner B runs at 2 meters/second, the distance between them increases by 1 meter every second.

Because the relative speed difference is exactly 1 step per tick:

  1. When both pointers enter a cycle of length C, the distance between them decreases by 1 step each iteration (gap = (gap - 1) % C).
  2. The fast pointer cannot "jump over" or skip past the slow pointer without landing on the exact same node!
  3. Therefore, if a cycle exists, slow and fast must collide within at most C iterations.
  4. If no cycle exists, fast or fast.next will inevitably hit null, signaling the linear end of the list.

Why Floyd's Algorithm Beats Hash Set

Using a Hash Set to store visited node references requires O(n) heap memory and can be restricted in systems with strict memory allocation limits. Floyd's cycle detection operates strictly with two pointer variables in O(1) auxiliary space without mutating node structures.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Initial State

slow and fast both start at head (node 3). List: 3 -> 2 -> 0 -> -4 (links back to 2).

State:slow = 3fast = 3
Strengths
  • +Optimal O(1) auxiliary space
  • +Requires zero node modifications or extra hash tables
Trade-offs
  • -Does not identify the exact entry point index of the cycle (solved in Linked List Cycle II)

Reference Implementation

Complete implementation for Floyd's Tortoise and Hare (Fast & Slow Pointers) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode | None) -> bool:
if not head or not head.next:
return False
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
if __name__ == "__main__":
# Create cycle: 3 -> 2 -> 0 -> -4 -> (points back to 2)
node1 = ListNode(3)
node2 = ListNode(2)
node3 = ListNode(0)
node4 = ListNode(-4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node2 # cycle back to node2
print("Has cycle:", has_cycle(node1))
Interactive Visualizer

Trace Circular Linked List mechanics in memory

Step through custom inputs in the Circular Linked List visualizer to inspect pointer updates, array shifts, and call-stack state alongside Linked List Cycle.

Open Circular Linked List visualizer

Frequently Asked Questions

Why is a 1-step relative speed gap between slow and fast crucial?

Inside the cycle, fast closes the remaining gap by 1 node every step ((gap - 1) % C). Because the step reduction is exactly 1, fast can never leapfrog over slow without intersecting it.

Could we solve this with a Hash Set instead?

Yes — storing visited node references in a Hash Set solves cycle detection cleanly in O(n) time, at the cost of O(n) extra heap memory compared to Floyd's O(1) space.

Why does `slow == fast` compare nodes rather than `slow.val == fast.val`?

Acyclical lists frequently contain duplicate integer values at different memory addresses. Only identical pointer/object identity proves two pointers landed on the same list node.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Empty list (head === null) and single node without loop ([1], pos = -1) return false.
  • Single node pointing to itself ([1], pos = 0) enters the loop and matches slow === fast immediately.
  • Tail loops all the way back to head vs looping into a mid-list node.
  • Two distinct nodes sharing the exact same Node.val inside an acyclic list — must compare pointer references, never node values.

Common Bugs to Avoid

  • Checking `while (fast.next != null)` instead of `while (fast != null && fast.next != null)`, crashing on `null` dereference when `fast` reaches null on even-length acyclic lists.
  • Comparing `slow.val == fast.val` instead of comparing object references (`slow == fast`), giving false positives on duplicate values.
  • Starting `fast = head.next` and testing `slow == fast` BEFORE advancing without realizing both work only if loop boundaries match.

Interview Follow-Up Variations

  • Linked List Cycle II: find the exact entry node where the cycle starts (reset one pointer to head upon collision and advance both +1 until they meet).
  • Find the Duplicate Number in a read-only length-(n+1) array with values 1..n by treating array indices as `next` pointers under Floyd's algorithm.

Related Problems

All problems
EasyLinked List

Reverse Linked List

Reverse a singly linked list in-place by flipping next pointers. Compare O(1)-space three-pointer iteration with recursive tail rewiring.

Pattern: Pointer Reversal
O(n) · O(1)
Solve
EasyLinked List

Merge Two Sorted Lists

Splice two sorted linked lists together into one non-decreasing linked list. Compare O(1)-space iterative dummy-head splicing against recursive pointer linking.

Pattern: Dummy Head
O(n + m) · O(1)
Solve
EasyTwo Pointers

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Pattern: Two Pointers Converging
O(n) · O(1)
Solve