Linked List Cycle
Detect a list that loops back on itself
DSA, Easy, Linked List
Which structure or algorithm, and what does it cost.
A linked list may loop back on itself. The examples describe a list with values and link. The last node's next pointer goes to the node at position link (counting from 0), or to null when link is -1. Return true if you can follow next pointers from the first node forever, and false if you reach null. Your method may use only the first node and the next pointers, never link. Use only O(1) extra memory.
Examples
Constraints
- 0 <= length of the list <= 100,000.
- Each value is a whole number between -1,000,000 and 1,000,000.
- -1 <= link < length of the list, and link is -1 for an empty list.
Your answer must contain
- The simple method and its memory cost; the method with O(1) memory and why it must meet inside a loop; code; time and memory cost; a hand trace of example 1 showing both pointers.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
If the list ends, the walk reaches null. If it loops, the walk never does. How can you tell the two cases apart without walking forever?
Hint 2 the approach
You could remember every node you have seen. To use no memory, think of two walkers on the list moving at different speeds.
Hint 3 the key step
Move one pointer one step and another two steps at a time. If they meet, there is a loop. If the fast one reaches null, there is none.
Walkthrough
Full walkthrough brute force to best
Brute force
Walk from the first node and store every node you pass in a set. If you reach a node that is already in the set, there is a loop. If you reach null, there is none. This takes O(n) time but O(n) memory for the set.
Best method
Use two pointers that start on the first node. Move slow one node at a time and fast two nodes at a time. If the list ends, fast reaches null first and the answer is false. If there is a loop, both pointers end up inside it. Inside a loop, fast gains one node on slow at every step, so the gap between them shrinks by one each time, and they must land on the same node. When slow and fast are the same node, the answer is true. This needs no set, only two pointers.
Hand trace
Run on values [3, 9, 4, 6] with link 1. Name the nodes N0 to N3, and N3 points back to N1. Both pointers start on N0. Step 1: slow moves to N1, fast moves to N2. They differ. Step 2: slow moves to N2, fast moves two steps, N3 then N1, and is on N1. They differ. Step 3: slow moves to N3, fast moves two steps, N2 then N3, and is on N3. Both are on N3, so the answer is true.
Code
class Node:
def __init__(self, val):
self.val = val
self.next = None
def has_cycle(values, link):
nodes = [Node(v) for v in values]
for i in range(len(nodes) - 1):
nodes[i].next = nodes[i + 1]
if nodes and link >= 0:
nodes[-1].next = nodes[link] # the last node links back to position link
slow = fast = nodes[0] if nodes else None
while fast and fast.next:
slow = slow.next # one step
fast = fast.next.next # two steps
if slow is fast:
return True
return FalseTime and memory
O(n) time: once both pointers are in the loop, they meet within one lap of it, and a lap has at most n nodes. O(1) extra memory: two pointers.
Common mistakes
- Comparing values instead of nodes. Different nodes can hold the same value, as in [5, 5, 5].
- Reading fast.next.next without checking fast.next first. On a list that ends, this reads past null.
- Comparing slow and fast before the first move. Both start on the first node, so they are always equal at that point.