Skip to content
Problem 141 · LeetCode 141(opens in a new tab)

Linked List Cycle

EasyHash tables

You get head, the first node of a singly linked list. Normally the last node's next is null. In a broken list, the last node points back to some earlier node instead, so following next from the head goes round and round forever.

Return true if the list has such a loop, and false if following next eventually reaches null. The tests describe the loop with pos, the index the last node links back to (−1 for none), but your function only receives head.

Example 1

Input:  head = [5, 8, 1, 6, 2], pos = 2
Output: true
Why:    the node holding 2 links back to the node holding 1
2 more examples and the constraints

Example 2

Input:  head = [4, 7], pos = 0
Output: true
Why:    7 links back to 4, the head

Example 3

Input:  head = [9, 3, 2], pos = -1
Output: false
Why:    after 2 comes null, so the walk ends

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • −100,000 ≤ node value ≤ 100,000
  • pos is −1 or a valid index into the list
  • Follow-up: use O(1) extra memory

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Remember visited nodesO(n)
  2. Slow and fast pointersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
Remember visited nodesO(n)
Passes; O(n) memory
Slow and fast pointersO(n)
Best; constant memory

n = number of nodes. Both are linear; the set also pays for hashing and storing every node.

Edge cases to test

  • Empty list. head is null: there is nothing to loop, so return false. Check fast before reading fast.next.
  • One node pointing at itself. [1] with pos 0 is a loop of length one and must return true.
  • Equal values, no loop. [3, 3, 3, 3] with pos −1 is false. A set of values would wrongly say true.
  • Tail points to itself. The loop can be just the last node; fast and slow still meet there.

Common mistakes

  • Storing node values in the set instead of the nodes, so repeated values look like a loop.
  • Reading fast.next.next without first checking that fast and fast.next are not null.
  • Comparing slow and fast before moving them, so the check succeeds at the head on step zero.

How to talk through it

  1. 1Clarify. Can the list be empty? Can values repeat? Is pos part of the input, or only of the test setup?
  2. 2Give the set version. Remember every node; a repeat means a loop. O(n) time and O(n) memory.
  3. 3Drop the memory. Two pointers at different speeds: a loop makes the fast one lap the slow one.
  4. 4Code it carefully. Guard fast and fast.next, move both, then compare the nodes by identity.
  5. 5Test out loud. Run the empty list, a single self-loop and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?