Practice Linked List Cycle for free
- 1,500+ real interview questions
- An adaptive learning engine
- Mock system design interviews
- Mock behavioral interviews
- Code in 14 languages
- Video and drawn walkthroughs
The problem
You are given head, the first node of a singly linked list. Return whether the list has a cycle.
A list has a cycle when some node can be reached again by following the next pointers. A list without a cycle ends: following the next pointers from the head reaches a node with no next node.
Each test gives the values of the list and an index pos. The test builds the list, links the
last node to the node at index pos, and then calls your method with the head. When
pos is -1, the last node links to nothing. Your method gets only head, not pos.
Constraints
- 0 <= number of nodes <= 10^4
- -10^5 <=
ListNode.data<= 10^5 - -1 <=
pos< number of nodes
Example
- Input
head = [3, 2, 0, -4], pos = 1- Output
true
The -4 links back to the 2, so following next from the head goes 3, 2, 0, -4, 2, 0, -4 and never ends.
How to solve it
Remembering every node
The first idea is to remember where you've been. Put every node you visit into a hash set, and if you reach one that's already in it, the list loops. On 3 → 2 → 0 → -4, the set takes all four nodes, then the -4's next pointer leads back to the 2, which is already there.
One trap: store the nodes, not their values. Four nodes that all hold 1, with no cycle, would look like a loop at the second node if you stored values. The set costs O(n) time and O(n) space. Give this answer first. The next question is whether you can do it in constant space.
How to detect a cycle in O(1) space
You can, keeping track of only two nodes. Start two pointers at the head. Slow moves one node per step and fast moves two. If the list ends, fast simply gets there first. If it loops, fast comes around behind slow and catches it. So if fast runs out of list there's no cycle, and if the two ever land on the same node there is. This is Floyd's tortoise and hare.
Run it on the example.
Linked List Cycle([3,2,0,-4], 1)
The run starts on [3,2,0,-4], 1.
Fast goes through the back link on its second step, and on the third both land on the -4. Two details the code has to get right. The loop runs while both fast and fast.next exist, so fast always has two safe steps to take; leaving out the second check is the classic bug. And the meeting test comes after the move, because both pointers start on the head. Compare with is, by node, for the same reason the set stored nodes.
Why fast can't jump over slow
A good interviewer will ask how you know fast can't jump right over slow and keep missing it. Once both pointers are inside the loop, think of fast as chasing slow from behind. The gap is how many nodes fast still has to make up. Every step, slow moves one and fast moves two, so the gap shrinks by exactly one. On the example it goes 2, 1, 0. A gap that only shrinks by one can't skip past zero, so fast has to land on slow. The gap also starts shorter than the loop, so they meet before slow finishes a single lap.
That bounds the cost too: slow takes at most n steps either way, so it's O(n) time, and two pointers are O(1) space.
Where does the cycle start?
The usual follow-up is to return the node where the cycle starts. Once the pointers meet, move one back to the head and leave the other where it is. Step both one node at a time, and the node where they meet again is the start of the cycle. On the example, one starts on the 3 and the other on the -4, and one step later both are on the 2.
Why it works: fast has gone twice as far as slow, and every extra step was spent going around the loop. So the steps slow has taken add up to a whole number of laps, and the meeting point is that many steps ahead of the head. Step both pointers at the same pace and that lead never changes, so the moment the one from the head enters the loop, the other is on the same node. It's O(n) time and O(1) space again.
Python solution
class Solution:
def has_cycle(self, head: ListNode) -> bool:
slow, fast = head, head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseTime and space complexity
- Time O(n)
- Without a cycle, fast reaches the end in about n/2 steps. With one, the pointers meet before slow finishes a lap.
- Space O(1)
- Two pointers, however long the list is.