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 true if the list has a cycle and false if it does not. A list has a cycle when following the next pointers from node to node comes back to a node already visited, so the walk never reaches the end.

The examples write the list as its values. "Tail connects to index 1" means the last node's next pointer leads back to the node at index 1, counting from 0.

Example 1
Input: head = [3, 2, 0, -4], tail connects to index 1
Output: true
Example 2
Input: head = [1, 2], tail connects to index 0
Output: true
Example 3
Input: head = [1], no cycle
Output: false
Solution

The Idea

A linked list is a chain of nodes. Each node holds a value and a pointer, named next, to the node after it. The last node, called the tail, normally has next set to null, and that null is how a walk along the list knows it has reached the end.

Follow Example 1 from the head: 3, then 2, then 0, then -4. The tail, -4, does not point to null. It points back to 2, the node at index 1, so the walk carries on: 2, 0, -4, 2, 0, -4, and so on, forever. That loop of three nodes is the cycle.

So how can code notice it is going round in circles? A walk that has not met null yet might be on a very long list, or might be on a loop. One answer is to remember every node visited: on a loop, some node comes up a second time. But there is a way that remembers nothing at all.

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: slow moves one node at a time and fast moves two. Look at the picture below.

The list 3, 2, 0, -4, whose tail points back to 2. After move 1 slow is at 2 and fast at 0. After move 2 slow is at 0 and fast at 2. After move 3 both are at -4 and meet.

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 fast reaches null, the list has an end. If fast lands on the same node as slow, the list has a cycle. Finding a cycle this way is known as Floyd's cycle detection, or the tortoise and hare algorithm.

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 fast cannot skip past slow, and how to tell that they met.

Remembering visited nodes

Why not keep the simple way? It puts each node it visits into a HashSet, Java's set that tells in one step whether it already holds an item. The walk stops when a node is already in the set (a cycle) or when it reaches null (no cycle). That is correct and takes one pass. But the set grows with the list: a list of a million nodes means a million stored references. The two pointers need two variables, however long the list is.

When to stop

When does fast stop moving? Each move takes it two nodes on, first to fast.next and then to fast.next.next. So the pointers keep moving only while fast != null and fast.next != null. If either check fails, the list has an end and the answer is false.

Why the pointers must meet

Could fast jump right over slow inside the cycle and never land on it? Once both are in the cycle, count how many nodes fast is behind slow. Each move, slow goes one node further and fast two, so that gap shrinks by exactly one.

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 has gone once round it.

Telling that they met

What counts as meeting? Both pointers must point at the same node object, so the test is slow == fast. On objects, Java's == is true only when both sides are the very same object. Comparing the values would not do, because two different nodes can hold the same value. The test also comes after the pointers move: both start at the head, so testing first would find them equal straight away.

Java Solution

The method hasCycle works in these steps:

  1. First, point two variables, slow and fast, at head.
  2. Start a loop that runs while fast != null && fast.next != null, so fast always has two nodes ahead to step through.
  3. Inside the loop, move slow one node with slow = slow.next, and fast two nodes with fast = fast.next.next.
  4. Right after moving, test slow == fast. If both are on the same node, return true.
  5. If the loop ends, fast has found the end of the list, so return false.

Around the method sit a small ListNode class and two helpers: build makes a list from an array and can point the tail back at a given index, and check prints each input with its answer.

The main method runs the three examples, an empty list, a single node that points to itself, four nodes with no cycle, and five nodes whose tail points to itself.

Java
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:

Output
[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] and [1, 2] print true, and the single node [1] prints false. Look at the [] line: an empty list makes head null, so the loop never starts and the answer is false.

The [7] line is one node whose next leads back to itself. After one move, slow and fast are both on 7 again, so it prints true. The last line is similar: the tail, 5, points to itself, a cycle of one node at the end of a longer list.

For [1, 2, 3, 4], fast goes from 1 to 3 in the first move and from 3 to null in the second, so the loop stops and the line prints false. That is why the loop checks fast != null and not only fast.next != null. A version with only the second check, tried on [1, 2] with no cycle, sends fast to null in one move, then reads fast.next and throws NullPointerException.

Complexity

The pointers move until fast finds the end or catches slow, and each move is a fixed amount of work.

  • Time: O(n), for a list of n nodes: without a cycle, fast runs off the end after about n/2 moves. With a cycle, slow enters it within n moves, and fast catches it before slow has gone once round, which is fewer than n more moves.
  • Space: O(1), because only slow and fast are kept, while a set of visited nodes would grow to n references.

Finding the node where the cycle starts takes one more short phase: see Linked List Cycle II.