Linked List Cycle
Tell whether a linked list loops back on itself, using a slow and a fast pointer and O(1) memory.
The problem
You get the head of a singly linked list. The last node may point back to an earlier node instead of ending, which creates a loop that never finishes. Return true if the list has such a cycle and false if it ends normally. In the examples, pos is the index of the node the tail links back to (-1 means no cycle); your function only receives head.
Input head = [5, 8, 1, 6, 9], pos = 2
Output true
The last node (9) links back to the node at index 2 (the 1).
Input head = [4, 7, 2], pos = -1
Output false
The list simply ends after 2.
Key constraint: Aim for O(1) extra memory, so no set of visited nodes.
How to spot the pattern
- You must find out whether following next pointers ever repeats a node.
- Walking a looped list never reaches the end, so "walk until null" alone can't answer it.
- The follow-up asks for constant extra memory.
The idea
Send two pointers down the list: slow moves one node per step and fast moves two. Without a cycle, fast simply runs off the end. With a cycle, both pointers end up going round the loop, and because fast gains one node on slow at every step, it has to land on slow sooner or later.
Brute force: Store every visited node in a hash set and stop when a node repeats, which is O(n) time but also O(n) extra memory.
Step by step
- 1Start
slowandfastathead. - 2While
fastandfast.nextboth exist, moveslowone step andfasttwo steps. - 3If they ever point to the same node, return
true. - 4If
fastreaches the end of the list, returnfalse.
See the pattern move
The fast and slow pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next # one step
fast = fast.next.next # two steps
if slow is fast:
return True
return FalseComplexity
Time
O(n)
Space
O(1)
Without a cycle fast reaches the end in about n/2 steps; with one, fast catches slow within one lap after slow enters the loop.
Watch out for
- Checking
fast.nextbefore checkingfast, which fails as soon asfastis already null. - Comparing node values instead of the nodes themselves: two different nodes can hold the same value.
- Comparing the pointers before moving them, which returns
truestraight away because both start athead.
Follow-up questions
How do you find the node where the cycle starts?
After slow and fast meet, move one pointer back to head and step both one node at a time; they meet at the start of the cycle. That is Linked List Cycle II.
How would you find the length of the cycle?
Once they meet, keep one pointer still and walk the other around the loop, counting steps until it comes back.
In Hinglish
Ek pointer dheere chalao, ek tez. Loop hua toh tez wala ghoom ke dheere wale ko pakad lega; loop nahi hai toh tez wala end tak pahunch jayega.