Skip to content

Linked List Cycle

EasyLeetCode #141Time O(n)Space O(1)

You get the head of a linked list. Some node’s next may point back to an earlier node, creating a loop. Return true if the list has a cycle, false if it ends.

3 -> 2 -> 0 -> -4 -> (back to 2) -> true
1 -> 2 -> 3 -> null -> false

The easy answer is a hash set of visited nodes: if you see one twice, there’s a cycle. That costs O(n) space. To use O(1), notice that a cycle is a loop, and runners on a loop eventually meet.

Move a slow pointer one step and a fast pointer two steps per turn (Floyd’s tortoise and hare). With no cycle, fast reaches the end and you return false. With a cycle, both enter it, and fast gains one node per turn on slow, so the gap shrinks by one each turn until they land on the same node.

Show solutionHide solution
def has_cycle(head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next # fast moves two steps per slow step
if slow is fast: # compare nodes, not values
return True
return False
  • Time: O(n) — without a cycle fast walks the list once. With one, slow reaches the cycle within n steps, and then fast closes the gap in at most the cycle length.
  • Space: O(1) — two pointers.
  • Check fast and fast.next before jumping two steps, or you dereference null on odd and even length lists.
  • Compare nodes, not values. [1, 1, 1] has equal values but no cycle.
  • Start both at head, and test for a meeting after moving. Testing before moving would report a cycle on every list immediately.
  • Empty list returns false because the loop never starts.

Return the node where the cycle begins. The trick: after slow and fast meet, reset one pointer to head. Move both one step at a time; they meet at the cycle’s start.

Return the middle node. The trick: same two speeds. When fast reaches the end, slow is at the middle. For an even length it lands on the second of the two middle nodes.

Repeatedly replace a number by the sum of its digits squared; does it reach 1? The trick: the sequence either hits 1 or loops forever. Treat “next number” as next and run Floyd’s algorithm, or use a set.