Linked List Cycle, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 141). Technique: tortoise and hare. Solution in Python, explained at every step.

The problem

You get the head of a linked list. Return whether it has a cycle: a node whose link leads back to a node earlier in the list, so that following the links never reaches the end.

Example: 3 → 6 → 6 → 9 → 5, where the last node, 5, links back to the second 6. Following the links goes 6, 9, 5, 6, 9, 5 … forever, so the answer is yes. If 5 linked to nothing, the answer would be no.

The list 3, 6, 6, 9, 5; the last node, 5, links back under the row to the second 6. Answer: yes. The same five nodes, with 5 linking to nothing. Answer: no.
The two 6s are different nodes: a cycle is about where a link goes, not about which values repeat.

Try it yourself first: LeetCode 141 ↗. Then step through the solution below.

Brute force

Walk the list and put every node into a hash set as you pass it: the nodes themselves, not their values, since two nodes can hold one value, as the example's two 6s do. If a node is already in the set, the walk has come back to it: a cycle. If the walk reaches the end, there is none. That is O(n) time but O(n) extra space for the set.

The key insight

The clue is in the words "following the links never reaches the end". With a cycle, a walk along the list goes round and round, so two walkers going round at different speeds must meet sooner or later. Without one, the faster walker reaches the end.

So walk with two variables: slow moves one node a turn, fast two. Once both are in the cycle, fast gains one node on slow every turn, so it cannot jump over it: the gap shrinks to 0 and they stand on the same node. This is Floyd's cycle detection, also called the tortoise and the hare; courses list it as the "fast and slow pointers" pattern.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Linked List Cycle, step by step

Python

class Node:    def __init__(self, val, next=None):        self.val, self.next = val, next def has_cycle(head):    slow = head    fast = head    while fast and fast.next:        slow = slow.next        fast = fast.next.next        if slow is fast:            return True    return False
All steps as text
  1. The last node, 5, links back to the second 6: a walk along the links never ends. Can code tell, keeping two variables?
  2. slow and fast both start at the head, 3. Each turn slow moves one node on, fast two.
  3. slow moves to the first 6, fast to the second 6. The same value, but two different nodes: they have not met.
  4. slow moves to the second 6, fast two nodes on, to 5. They are not at the same node.
  5. slow moves to 9. fast takes the link from 5 back to the second 6, then on to 9.
  6. slow and fast are at the same node, 9: only a cycle brings fast round to slow. The answer is yes.
  7. Inside the cycle fast gains a node a turn, so it meets slow within one lap: O(n) time, O(1) space.
Linked List Cycle, step by step. Last step: Inside the cycle fast gains a node a turn, so it meets slow within one lap: O(n) time, O(1) space.

Complexity

ApproachTimeSpace
Brute force: a hash set of the nodes passedO(n)O(n)
Two variables, one moving twice as fast this pageO(n)O(1)
  • Time: O(n). slow reaches the cycle within n moves, and fast catches it within one more lap; without a cycle, fast reaches the end in n / 2 turns.
  • Space: O(1). Two variables, whatever the length of the list.

Edge cases

  • An empty list: fast starts at no node (∅), the loop never runs, and the answer is no.
  • A single node linking to nothing: there is no node after fast (∅), so the loop never runs: no.
  • A single node linking to itself: in the first turn both move to that same node, and the test says yes.
  • A cycle through the whole list, the last node linking back to the head: fast laps the list and meets slow within n turns.

When the answer is no

The same nodes, with the last one, 5, linking to nothing. Press → for each step.

Linked List Cycle, when the answer is no

Python

class Node:    def __init__(self, val, next=None):        self.val, self.next = val, next def has_cycle(head):    slow = head    fast = head    while fast and fast.next:        slow = slow.next        fast = fast.next.next        if slow is fast:            return True    return False
All steps as text
  1. The last node, 5, links to nothing (∅). Does the list have a cycle?
  2. slow and fast both start at the head, 3. Each turn slow moves one node on, fast two.
  3. slow moves to the first 6, fast to the second 6. The same value, but two different nodes: they have not met.
  4. slow moves to the second 6, fast two nodes on, to 5. They are not at the same node.
  5. fast is at 5, the last node: the node after it is ∅, so the loop is over. No cycle: the answer is no.
  6. fast reached the end in two turns, about half as many as there are nodes: O(n) time, O(1) space.
Linked List Cycle, when the answer is no. Last step: fast reached the end in two turns, about half as many as there are nodes: O(n) time, O(1) space.

Try it: put Linked List Cycle together step by step

The blocks below are steps of Linked List Cycle in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example, on the same nodes with 5 linking to nothing, and on 4 → 7 → 4 → 1 → 8, which ends at nothing too, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Linked List Cycle together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

Where does the cycle start? That is Linked List Cycle II (LeetCode 142). Once they meet, put one variable back at the head and move both one node a turn: they meet again exactly at the node where the cycle starts. Why: when they meet, slow has made a moves to the cycle's start and b more inside it, and fast twice as many: the same a + b plus whole laps. So a + b is whole laps, and from the meeting point a more moves lead back to the start. Still O(n) time and O(1) space.

The data structure behind it

  • Linked list: nodes, links and how a walk follows them, step by step.