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, next, to the node after it. Given head, the first node of a linked list, return the node where the list's cycle begins, or null if it has no cycle. A list has a cycle when following next leads back to a node already visited, so the walk never reaches an end. The list must not be modified.

Each example gives the values in order and says where the last node's next points, by the index of that node (its position, counting from 0).

Example 1
Input: head = [3, 2, 0, -4], tail connects to index 1
Output: the node with value 2
Example 2
Input: head = [1, 2], tail connects to index 0
Output: the node with value 1
Example 3
Input: head = [1], no cycle
Output: null
Solution

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, slow and fast. Each round, slow moves one node and fast moves two. Without a cycle, fast runs off the end of the list. With a cycle, both end up going round the loop, and fast closes in on slow until they stand on the same node. Meeting at all proves there is a cycle, which is all that Linked List Cycle asks.

In Example 1, slow visits 2, 0 and -4, while fast visits 0, 2 and -4. After three rounds both are on -4. They met, but not at 2, where the cycle starts. How do we get from the node where they met to the start of the cycle? Look at the picture below.

The list 3, 2, 0, -4, where the last node points back to 2, a cycle of 3 nodes. The head is 3, the cycle start is 2, and slow and fast meet at -4, the meeting point. a, from the head to the cycle start, is 1 step. b, from the cycle start to the meeting point, is 2 steps.

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, slow had walked a + b = 3 steps and fast twice as far, 6 steps. They stand on the same node, so the 3 extra steps of fast must be whole laps around the cycle. The same holds for any list: fast's extra distance is a + b, so a + b is a whole number of laps.

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 slow and fast meet, put one pointer on the head and one on the meeting point and move both one node at a time. They meet exactly at the cycle start, and we never need to know a, b or c. This method is known as Floyd's cycle detection, and the two pointers are often called the tortoise and the hare.

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 HashSet, a Java set that tells in one step whether it already holds something. The first node that is already in the set is the cycle start. The set must hold nodes, not values, because different nodes can have the same value. It finds the answer in one walk, but for a list of n nodes it stores up to n of them. The pointer method needs only three pointers, slow, fast and one more for the walk from the head, however long the list is.

Detecting the cycle

When does the first walk stop? fast jumps two nodes at a time, so it needs both fast and fast.next to exist. If either is null, the list has an end, so there is no cycle and the answer is null.

Could fast jump over slow inside the cycle and miss it? Once both are in the cycle, each round fast moves two nodes and slow one, so the gap between them shrinks by exactly one node. A gap that shrinks one at a time reaches zero; it cannot skip past it.

Walking to the cycle start

Which pointers make the second walk? A new pointer, p, starts at the head, and slow stays on the meeting point. Both move one node per round until they are on the same node. They cannot meet too early: while p is still on the straight part, slow is inside the cycle.

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 slow and fast meet on the cycle start, which is the head itself. p and slow are already together, the second walk takes no steps, and the head is returned.

Java Solution

The method detectCycle works in these steps:

  1. First, start two pointers, slow and fast, at head.
  2. In a while loop that runs as long as fast and fast.next are not null, move slow one node and fast two nodes.
  3. After each move, check slow == fast. This compares the nodes themselves, not their values. When it is true, the two pointers have met inside the cycle.
  4. Then, still inside the first loop, start a new pointer, p, at head. A second while loop moves p and slow one node each until p == slow. Return p: it is the cycle start.
  5. If the first loop ends because fast reached the end of the list, return null.

Around the method sit a small ListNode class and two helpers. build makes a list from the values and the index the last node points to, with -1 for no cycle. describe prints the returned node's index and value.

The main method runs the three examples, a single node that points to itself, an empty list, a ten-node list with a long straight part, and a list whose values are all 5.

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

Output
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 2: that is the cycle start from the picture, even though slow and fast met at -4. In the second line the answer is the head itself, index 0, and the third line is null because the one-node list in Example 3 has an end.

The single node 7 that points to itself gives node at index 0, value 7: after one round, both slow and fast are back on it. The empty list prints null, because fast starts out as null and the loop never runs.

The ten-node list, 1 to 10, has its last node point back to index 7, so the cycle is 8, 9, 10. Here slow and fast meet at 10 after nine rounds. Then p needs seven steps from the head to reach 8. In those seven steps, slow moves from 10 to 8 and then goes round the three-node cycle twice more, so a + b = 9 is three whole laps here. Both pointers arrive at 8, and the line reads node at index 7, value 8.

The last line, node at index 2, value 5, comes from four nodes that all hold 5. Only comparing the nodes themselves can tell them apart, and the index shows that the right one was found.

Complexity

The work is the two walks: one until slow and fast meet, and one from the head to the cycle start.

  • Time: O(n) for a list of n nodes: once slow enters the cycle, fast is less than one lap behind it and gains a node every round, so they meet before slow finishes its first lap, within n rounds. The second walk takes a steps, fewer than n.
  • Space: O(1). The method keeps three pointers, slow, fast and p, where the simple way kept a set with up to n nodes.

The same two walks find the repeated number in Find the Duplicate Number, where each number in the array is read as a pointer to the next position.