Linked List Cycle
Linked List Cycle is LeetCode 141 (Easy). Given the head of a singly linked list, return true if following the next pointers ever brings you back to a node you have already passed, and false if the walk ends at null.
posin the examples only says where the last node links back to; it is not passed to your function.- The list has up to 10⁴ nodes, and the follow-up asks for O(1) extra memory.
- The number of the nodes in the list is in the range [0, 10⁴].
- -10⁵ <= Node.val <= 10⁵
- pos is -1 or a valid index in the linked-list.
Intuition
A list with a loop never reaches null, so walking it to the end never finishes. Send two pointers instead: slow moves one node per round and fast moves two.
- No loop:
fastis always ahead, so it reaches the end first and the walk stops withfalse. - Loop: both pointers end up going round it. Each round,
fastcloses the gap toslowby exactly one node, so the gap counts down 3, 2, 1, 0 and cannot skip past zero. The pointers land on the same node, which only a loop allows.
"Does this sequence of next steps ever repeat?" with no room for a visited set is the fast and slow pointer pattern. The same trick finds a repeated number in Happy Number and Find the Duplicate Number.
Approach
Before reading on, write the version that remembers every node it has seen. Then ask what two pointers moving at different speeds would do if the list loops. Aim for O(n) time and O(1) space.
Two ways to solve it
Move one pointer by one node and the other by two; a meeting means a loop.
- Memory: two pointers.
- Leaves the list unchanged.
The answer to the follow-up.
Walk the list and remember every node; meeting one again means a loop.
- Simple: one pointer and one set.
- Cost: up to 10⁴ stored nodes.
The natural first idea.
Both take O(n) time. The two-pointer walk is shown first because it meets the O(1) memory follow-up; the visited-set version comes after the demo.
Run while fast can take two steps
Start slow and fast at head and loop while fast and fast.next both exist. fast is the pointer that reaches the end first, so these two checks are where a list without a loop stops, and they keep fast.next.next from reading past the end.
Move slow by one and fast by two
Each round, set slow = slow.next and fast = fast.next.next. The difference of one node per round is what makes the gap inside a loop shrink steadily instead of staying the same forever.
Compare the nodes, not their values
After moving, return true if slow is fast. Different nodes can hold the same value, as in 1 → 2 → 1 with no loop, so only the same node object proves the walk came back.
Return false when the loop ends
Leaving the while loop means fast found the end of the list, and a list with an end has no loop. Without a loop this happens after about n / 2 rounds.
Code in Python, C++ and Java
fast still needs to catch up with slow once both are in the loop.fast needs 2 more nodes to reach slow, and each round it gains exactly one, so the gap can only count down to 0.fast needs 1 more node to reach slow, and each round it gains exactly one, so the gap can only count down to 0.fast still needs to catch up with slow once both are in the loop.slow moved one node and fast two. They are on different nodes, so the walk goes on. slow has not reached the loop yet, so the gap is not counted.fast needs 3 more nodes to reach slow, and each round it gains exactly one, so the gap can only count down to 0.fast needs 2 more nodes to reach slow, and each round it gains exactly one, so the gap can only count down to 0.fast needs 1 more node to reach slow, and each round it gains exactly one, so the gap can only count down to 0.slow moved one node and fast two. They are on different nodes, so the walk goes on.slow moved one node and fast two. They are on different nodes, so the walk goes on.fast cannot take two more steps because the list ends after node 5. A list with an end has no loop, so return false. Checking fast.next as well as fast is what stops the code here instead of reading past the end.Set of visited nodes
Walk the list once and store each node object in a set. A node that is already in the set means the walk has come back, so there is a loop. Reaching None means the list ends. The set holds nodes, not values, because values can repeat.
Common pitfalls
Comparing before moving
while fast and fast.next:
if slow is fast:
return True
slow = slow.next
fast = fast.next.nextwhile fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return TrueBoth pointers start on head, so the first comparison is always true. On [1, 2] with no loop this returns true before either pointer has moved.
Checking only fast in the loop condition
while fast:
slow = slow.next
fast = fast.next.nextwhile fast and fast.next:
slow = slow.next
fast = fast.next.nextOn [1, 2, 3] with no loop, round one puts fast on node 3. Its next is None, so round two reads None.next and crashes. Any list without a loop and with an odd number of nodes fails this way.
Edge cases
head is None, so the loop condition fails at once and the answer is false.
After one round both pointers are back on that node, so the answer is true.
Complexity
slow first walks the part of the list before the loop. Once both are in the loop, fast is less than one lap behind and gains one node per round, so slow is caught before it finishes a single lap. That is at most n rounds, with two pointers of extra memory.Linked List Cycle FAQ
How is this different from finding where the loop starts?
This problem only asks whether a loop exists, so the first meeting of slow and fast is enough. Linked List Cycle II (LeetCode 142) asks for the node where the loop begins. The meeting node is usually somewhere else in the loop, so 142 adds a second walk from the head to find the start.
Does fast have to move exactly two nodes?
No. When both start at the head, after t rounds they are t and k·t nodes along. Once both are in the loop, any round t that is a multiple of the loop length puts them on the same node, so they always meet. Two is used because it needs the fewest next reads per round and only two null checks.