Skip to content
mlmentorship

Detect a cycle with one-link and two-link moves

Follow actual node identities, prove the relative-offset collision, then recover the cycle entry and length without changing links.

Published · 14 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Detect a cycle with one-link and two-link moves

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A ListNode head reference, or None, with stable next links that may form a cycle. Output. Return True if a node can be visited again by following next; otherwise return False. Rules. Compare node identity, not stored values: two different nodes may contain the same value. Do not change links or retain every visited node; use constant auxiliary pointer storage. An empty list returns False. A node pointing to itself returns True. Example. For 1 -> 2 -> 3 -> 4 with 4.next pointing to the existing node 2, return True. Four distinct nodes with no backward link return False, even if two values are equal.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

With a cycle, a pointer moving two links per round gains one cycle position on a pointer moving one link, so they must meet.

Problem trace

Matching node identities after valid moves reveals a cycle

Input and goalCheck whether a linked list contains a cycle.
Initialize both pointers at headStart both pointers at node 1 without comparing them. Guard the two-link move before advancing.
Linked-list topologyNodes, next pointers, and moving algorithm pointers.next4.next -> 2slowfast1234
slowAt1fastAt1guardfast=1 and fast.next=2
edges
[node-1 -> node-2, node-2 -> node-3, node-3 -> node-4, node-4 -> node-2]
slow at
1
fast at
1

Recognize it
Use it for cycle detection in a deterministic next-pointer structure when constant extra space is required and storing every visited node would be unnecessary.
Keep true
After r loop iterations, slow has followed r next links and fast has followed 2r. If no cycle exists fast reaches null; inside a cycle their relative offset changes by one per round.
Reuse it
Different traversal speeds convert a hidden cycle into an inevitable identity collision; guard every fast hop. The technique transfers to repeated-state sequences and cycle-entry algorithms.
Start both pointers at node 1 without comparing them. Guard the two-link move before advancing. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does co-location at initialization prove nothing, while the later identity match after valid moves proves a cycle?
Full interview answer 14 min read

Determine whether repeatedly following a linked list’s next references eventually revisits the same node.

Problem

Input. A ListNode head reference, or None, with stable next links that may form a cycle.

Output. Return True if a node can be visited again by following next; otherwise return False.

Rules. Compare node identity, not stored values: two different nodes may contain the same value. Do not change links or retain every visited node; use constant auxiliary pointer storage. An empty list returns False. A node pointing to itself returns True.

Example. For 1 -> 2 -> 3 -> 4 with 4.next pointing to the existing node 2, return True. Four distinct nodes with no backward link return False, even if two values are equal.

Picture

Let slow follow one link per round and fast follow two. Both start at the head, so initial equality cannot distinguish a cycle from an ordinary list. Compare only after moving.

Completed roundslow nodefast node
011; not compared
123
232
344; identity collision

Once both references enter a cycle of length , their relative offset changes by one modulo each round. It reaches zero within further rounds. Without a cycle, fast eventually reaches a missing link instead.

Problem trace

Separate identity check: equal values do not merge distinct nodes

Worked example: compare node identity, not repeated stored valuesTwo distinct nodes may both store value 7. A cycle witness requires the slow and fast pointers to reach the same node identity after valid moves.Equal values do not merge twodistinct objects7node Aslow7node BfastAfter valid moves, both pointers canreach one shared C7slowfastone node C
Read it this way: Two distinct nodes may both store value 7. A cycle witness requires the slow and fast pointers to reach the same node identity after valid moves. Do matching stored sevens prove that slow and fast reference the same object?
Reference drawing

Problem trace

Matching node identities after valid moves reveals a cycle

Worked example: compare node identity, not repeated stored valuesTwo distinct nodes may both store value 7. A cycle witness requires the slow and fast pointers to reach the same node identity after valid moves.Equal values do not merge twodistinct objects7node Aslow7node BfastAfter valid moves, both pointers canreach one shared C7slowfastone node C
Execution trace
Input and goalCheck whether a linked list contains a cycle.
Initialize both pointers at headStart both pointers at node 1 without comparing them. Guard the two-link move before advancing.
Linked-list topologyNodes, next pointers, and moving algorithm pointers.next4.next -> 2slowfast1234
slowAt1fastAt1guardfast=1 and fast.next=2
edges
[node-1 -> node-2, node-2 -> node-3, node-3 -> node-4, node-4 -> node-2]
slow at
1
fast at
1

Recognize it
Use it for cycle detection in a deterministic next-pointer structure when constant extra space is required and storing every visited node would be unnecessary.
Keep true
After r loop iterations, slow has followed r next links and fast has followed 2r. If no cycle exists fast reaches null; inside a cycle their relative offset changes by one per round.
Reuse it
Different traversal speeds convert a hidden cycle into an inevitable identity collision; guard every fast hop. The technique transfers to repeated-state sequences and cycle-entry algorithms.
Start both pointers at node 1 without comparing them. Guard the two-link move before advancing. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does co-location at initialization prove nothing, while the later identity match after valid moves proves a cycle?
Read it this way: Two distinct nodes may both store value 7. A cycle witness requires the slow and fast pointers to reach the same node identity after valid moves. Do matching stored sevens prove that slow and fast reference the same object?

Code

The platform supplies this node contract; use the definition below when running these blocks together locally.

class ListNode:
   def __init__(self, val=0, next=None):
      self.val = val
      self.next = next
def has_cycle(head: ListNode | None) -> bool:
   slow = head
   fast = head

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

The guard makes both link dereferences safe; the second hop may return None.

is compares object identity, not stored values or custom equality. For reachable nodes, the function uses link operations and extra storage.

Failure Check

Two distinct acyclic nodes both valued 7 still return False. Comparing values, or comparing the shared head before movement, would give a false cycle certificate.

Change to Entry Identity

New task: Return the original node where the cycle begins, or None.

Picture and change: After collision, reset one reference to the head and advance both by one link. At collision, the faster reference’s extra distance is a multiple of the cycle length. If the entry is links from the head, another links from the collision also reaches that entry.

def cycle_entry(head):
   slow = fast = head
   while fast and fast.next:
      slow, fast = slow.next, fast.next.next
      if slow is fast:
         entry = head
         while entry is not slow:
            entry, slow = entry.next, slow.next
         return entry
   return None

Check: The example returns the original node 2, not a new node with value 2. The collision occurs at node 4, showing that collision and entry need not coincide.

Use when: The repeated component needs a node-identity witness.

Change to Cycle Length

New task: Count distinct nodes in the cycle, excluding the noncyclic prefix.

Picture and change: Use cycle_entry above, then count one traversal back to that same node.

def cycle_length(head):
   entry = cycle_entry(head)
   if entry is None:
      return 0
   length, node = 1, entry.next
   while node is not entry:
      length += 1
      node = node.next
   return length

Check: The example returns 3; a self-loop returns 1, and an acyclic list returns 0. Both adaptations retain linear link work, constant extra storage and all original links.

Use when: The repeated-state period is the required quantity.

Transfer Check

Why is gaining exactly one relative link useful inside the cycle?

Answer

Successive offsets visit every residue modulo its length, including zero. The proof concerns positions on next links, not numeric values or visual proximity.