Linked List Cycle

Easy

Topics
Linked ListTwo PointersHash Table

Given the head of a linked list, return true if it has a cycle. On this judge the input is the node values plus pos — the index the tail’s next connects to, or -1 for no cycle. pos is not passed to your function.

Example 1

320-4cycle
where the tail points back
The tail links back to index 1, so the list has no end and the answer is true.
Values from head to tail; a curved edge underneath would mark a cycle.
Input:  head = [3,2,0,-4], pos = 1
Output: true

Example 2

1null
The list ends at null, so the answer is false. The fast pointer reaching the end is the proof; the pos = -1 in the input is what says there is no back-edge.
Input:  head = [1], pos = -1
Output: false

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Use Floyd’s tortoise and hare: a slow pointer moving one step and a fast pointer moving two. If there is a cycle the fast pointer eventually laps the slow one; if not, it reaches the end.

Approach

  1. Advance slow by 1 and fast by 2 each iteration.
  2. If fast (or fast.next) becomes null, there is no cycle.
  3. If slow and fast ever meet, there is a cycle.

Dry Run

3 -> 2 -> 0 -> -4, and the -4 points back at the 2
  index     0    1    2    3
  value     3    2    0   -4
  start    slow index 0     fast index 0
  step 1   slow index 1     fast index 2
  step 2   slow index 2     fast index 1     fast has wrapped round
  step 3   slow index 3     fast index 3     they meet  -> true
fast gains exactly one position on slow every step, so once both pointers are
inside the loop the gap between them shrinks by one per step and has to reach
zero. That is the entire argument, and it is why no step counter and no visited
set are needed. Watch fast wrap from index 2 to index 1 at step 2 while slow is
still working its way in.
The acyclic case is handled by the loop condition, not by a separate branch. On
1 -> 2 the first step lands fast on index 1, whose next is null, so
`while fast and fast.next` fails and the function returns false. Both halves of
that test are needed: fast itself can be null after a double step, or fast can be
sitting on the final node with nowhere to jump.

Complexity

  • Time — O(n): the pointers meet within a linear number of steps.
  • Space — O(1): two pointers, no extra structure (beats the hash-set approach on space).

Common Pitfalls

  • Check both fast and fast.next before the double step to avoid a null dereference.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def hasCycle(self, head):
        slow=fast=head
        while fast and fast.next:
            slow=slow.next; fast=fast.next.next
            if slow is fast: return True
        return False
SensAI
Beta
Tap the mic to stop voice mode