Linked List Cycle II
Find the node where a linked list starts going round in a loop, using two pointers and no extra memory.
A linked list is a chain of nodes: each node holds a value and a pointer, nextheadnullnext
Each example gives the values in order and says where the last node's next
Example 1
Output: the node with value 2
Example 2
Output: the node with value 1
Example 3
Output: null
The Idea
Think of a road that leads into a roundabout. You drive along the road, enter the circle and keep going round it, and the drive never ends. A linked list with a cycle has the same shape: a straight part from the head, then a loop. The question is where the road joins the circle.
In Example 1 the values are 3, 2, 0 and -4, and the last node, -4, points back to index 1, the node with value 2. Walking from the head visits 3, 2, 0, -4, 2, 0, -4, 2 and so on forever. The cycle starts at 2, the first node that the walk visits a second time.
That suggests a simple way: remember every node you pass, and stop at the first one you meet again. It works, but it needs memory for every node. Can a couple of pointers do the job instead?
Start two pointers at the head, slowfastslowfastfastfastslow
In Example 1, slowfast
The bracket labelled a = 1 step is the distance from the head to the cycle start, from 3 to 2. The bracket labelled b = 2 steps runs from the cycle start to the meeting point, from 2 through 0 to -4. The arrow along the top closes the cycle, which has c = 3 nodes.
When the two pointers met, slowfastfast
Now let a pointer at the meeting point walk a more steps. It is then a + b steps past the cycle start, a whole number of laps, so it is back on the cycle start. A pointer at the head that walks a steps lands on the cycle start too. In the picture, one step from 3 reaches 2, and one step from -4, along the top arrow, reaches 2 as well.
So after slowfast
Solution Approach
Turning that idea into code means weighing the simple way of remembering nodes against the pointers, then settling how to detect the cycle and how to walk to its start.
Remembering visited nodes
What would the simple way cost? Put every node you pass into a HashSetslowfast
Detecting the cycle
When does the first walk stop? fastfastfast.nextnullnull
Could fastslowfastslow
Walking to the cycle start
Which pointers make the second walk? A new pointer, pslowpslow
What if the cycle starts at the head, as in Example 2? Then a is 0, so b alone is a whole number of laps, and slowfastpslow
Java Solution
The method detectCycle
- First, start two pointers,
andslow , atfast .head - In a
loop that runs as long aswhile andfast are notfast.next , movenull one node andslow two nodes.fast - After each move, check
. This compares the nodes themselves, not their values. When it is true, the two pointers have met inside the cycle.slow == fast - Then, still inside the first loop, start a new pointer,
, atp . A secondhead loop moveswhile andp one node each untilslow . Returnp == slow : it is the cycle start.p - If the first loop ends because
reached the end of the list, returnfast .null
Around the method sit a small ListNodebuilddescribe
The main
public class LinkedListCycleII {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // one step
fast = fast.next.next; // two steps
if (slow == fast) { // they met inside the cycle
ListNode p = head;
while (p != slow) { // same distance to the cycle start
p = p.next;
slow = slow.next;
}
return p;
}
}
return null; // fast fell off the end: no cycle
}
// Builds a list from values; the last node points to index pos (-1: no cycle).
static ListNode build(int[] values, int pos) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
ListNode target = null;
for (int i = 0; i < values.length; i++) {
tail.next = new ListNode(values[i]);
tail = tail.next;
if (i == pos) target = tail;
}
tail.next = target;
return dummy.next;
}
// Describes the returned node by its index and value, or prints null.
static String describe(ListNode head, ListNode node) {
if (node == null) return "null";
int index = 0;
for (ListNode p = head; p != node; p = p.next) index++;
return "node at index " + index + ", value " + node.val;
}
static void run(int[] values, int pos) {
ListNode head = build(values, pos);
System.out.println(describe(head, detectCycle(head)));
}
public static void main(String[] args) {
run(new int[] {3, 2, 0, -4}, 1);
run(new int[] {1, 2}, 0);
run(new int[] {1}, -1);
run(new int[] {7}, 0); // one node pointing to itself
run(new int[] {}, -1); // empty list
run(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 7);
run(new int[] {5, 5, 5, 5}, 2); // equal values
}
}
Running it prints:
node at index 1, value 2
node at index 0, value 1
null
node at index 0, value 7
null
node at index 7, value 8
node at index 2, value 5
Look at the first line, node at index 1, value 2slowfastnull
The single node 7 that points to itself gives node at index 0, value 7slowfastnullfastnull
The ten-node list, 1 to 10, has its last node point back to index 7, so the cycle is 8, 9, 10. Here slowfastpslownode at index 7, value 8
The last line, node at index 2, value 5
Complexity
The work is the two walks: one until slowfast
- Time: O(n) for a list of n nodes: once
enters the cycle,slow is less than one lap behind it and gains a node every round, so they meet beforefast finishes its first lap, within n rounds. The second walk takes a steps, fewer than n.slow - Space: O(1). The method keeps three pointers,
,slow andfast , where the simple way kept a set with up to n nodes.p
The same two walks find the repeated number in