Linked List Cycle
Tell whether a linked list loops back on itself, using two pointers that move at different speeds.
Given the head of a linked list, return truefalsenext
The examples write the list as its values. "Tail connects to index 1" means the last node's next
Example 1
Output: true
Example 2
Output: true
Example 3
Output: false
The Idea
A linked list is a chain of nodes. Each node holds a value and a pointer, named nextnextnullnull
Follow Example 1 from the head: 3, then 2, then 0, then -4. The tail, -4, does not point to null
So how can code notice it is going round in circles? A walk that has not met null
Think of two people on a running track, one running twice as fast as the other. On a straight road the faster one simply reaches the end first. On a circular track there is no end, so the faster one comes round and catches up with the slower one from behind.
Do the same with two pointers into the list: slowfast
In the row labelled "start", both pointers are on 3, the head. After move 1, slow is on 2 and fast has jumped to 0. In move 2, fast goes from 0 to -4 and then along the orange arrow, labelled "the tail points back to 2", to 2, so it is now behind slow, which is on 0. In move 3, slow steps to -4, and fast jumps from 2 over 0 to -4 as well. The row labelled "after move 3" shows them meeting.
So the whole question comes down to which happens first. If fastnullfastslow
Solution Approach
Turning that idea into code starts with a look at the simple way, then settles three things: when to stop moving the pointers, why fastslow
Remembering visited nodes
Why not keep the simple way? It puts each node it visits into a HashSetnull
When to stop
When does fastfast.nextfast.next.nextfast != nullfast.next != nullfalse
Why the pointers must meet
Could fastslowfastslowslowfast
A gap of 3 becomes 2, then 1, then 0, and a gap of 0 means both are on the same node. The gap starts smaller than the length of the cycle, so they meet before slow
Telling that they met
What counts as meeting? Both pointers must point at the same node object, so the test is slow == fast==
Java Solution
The method hasCycle
- First, point two variables,
andslow , atfast .head - Start a loop that runs while
, sofast != null && fast.next != null always has two nodes ahead to step through.fast - Inside the loop, move
one node withslow , andslow = slow.next two nodes withfast .fast = fast.next.next - Right after moving, test
. If both are on the same node, returnslow == fast .true - If the loop ends,
has found the end of the list, so returnfast .false
Around the method sit a small ListNodebuildcheck
The main
public class LinkedListCycle {
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public static boolean hasCycle(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) {
return true; // fast caught up with slow inside a loop
}
}
return false; // fast reached the end of the list
}
// Builds a list from vals; the last node points back to index pos (-1: no cycle).
static ListNode build(int[] vals, int pos) {
ListNode[] nodes = new ListNode[vals.length];
for (int i = 0; i < vals.length; i++) {
nodes[i] = new ListNode(vals[i]);
if (i > 0) {
nodes[i - 1].next = nodes[i];
}
}
if (pos >= 0) {
nodes[vals.length - 1].next = nodes[pos];
}
return vals.length == 0 ? null : nodes[0];
}
static void check(int[] vals, int pos) {
String link = pos >= 0 ? "tail -> index " + pos : "no cycle";
System.out.println(java.util.Arrays.toString(vals) + ", " + link + ": "
+ hasCycle(build(vals, pos)));
}
public static void main(String[] args) {
check(new int[] {3, 2, 0, -4}, 1);
check(new int[] {1, 2}, 0);
check(new int[] {1}, -1);
check(new int[] {}, -1);
check(new int[] {7}, 0);
check(new int[] {1, 2, 3, 4}, -1);
check(new int[] {1, 2, 3, 4, 5}, 4);
}
}
Running it prints:
[3, 2, 0, -4], tail -> index 1: true
[1, 2], tail -> index 0: true
[1], no cycle: false
[], no cycle: false
[7], tail -> index 0: true
[1, 2, 3, 4], no cycle: false
[1, 2, 3, 4, 5], tail -> index 4: true
The examples come out as expected: [3, 2, 0, -4][1, 2]true[1]false[]headnullfalse
The [7]nextslowfasttrue
For [1, 2, 3, 4]fastnullfalsefast != nullfast.next != null[1, 2]fastnullfast.nextNullPointerException
Complexity
The pointers move until fastslow
- Time: O(n), for a list of n nodes: without a cycle,
runs off the end after about n/2 moves. With a cycle,fast enters it within n moves, andslow catches it beforefast has gone once round, which is fewer than n more moves.slow - Space: O(1), because only
andslow are kept, while a set of visited nodes would grow to n references.fast
Finding the node where the cycle starts takes one more short phase: see