Article start
DSA Course: Interview Patterns and Problem Solving
Module 5: Linked List

Linked List Cycle: Fast and slow pointers Pattern

Detect a cycle by moving one pointer twice as fast as the other.

May 28, 2026·31

Learning Outcome

After this lesson, you should be able to explain why fast and slow pointers meet if a linked list contains a cycle.

Problem Statement

Given the head of a linked list, return true if the list has a cycle. A cycle means a node's next pointer points back to an earlier node.

Input shapeOutputWhy
3 -> 2 -> 0 -> -4, where -4 points back to 2trueThe list loops forever.
1 -> 2 -> nullfalseThe list ends normally.

Brute Force Approach

Store every visited node in a set. If the same node appears again, there is a cycle.

This is easy and correct, but it uses O(n) extra space.

Optimized Approach

Use Floyd's cycle detection. Move slow one step and fast two steps. If there is a cycle, fast eventually catches slow. If there is no cycle, fast reaches null.

Exact Pseudocode

slow = head
fast = head
while fast is not null and fast.next is not null:
  slow = slow.next
  fast = fast.next.next
  if slow == fast:
    return true
return false

Reference Code

class Solution:
    def hasCycle(self, head):
        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True

        return False

Sample Dry Run

StepslowfastResult
Start33Begin
120Not equal
202Not equal
3-4-4Equal, cycle exists

Complexity

MeasureValueReason
TimeO(n)The pointers traverse at most linear distance before ending or meeting.
SpaceO(1)No visited set is needed.

Edge Cases

  • Empty list.
  • Single node with no cycle.
  • Single node pointing to itself.

Interview Checklist

  • Check fast and fast.next before moving two steps.
  • Compare node references, not values.
  • Explain why fast catches slow inside a cycle.

FAQs

Why do fast and slow meet in a cycle?

Inside the cycle, fast gains one node on slow each iteration, so the gap eventually becomes zero.

Why compare nodes instead of values?

Different nodes can have the same value. A cycle is about references, not values.

What is the core pattern?

Floyd's fast and slow pointer cycle detection.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.