Linked List · Pattern 2 of 5

Fast and slow pointers: middles and cycles

Move one pointer one step and another two steps. When the fast one reaches the end, the slow one is in the middle. If there is a cycle, the fast one laps the slow one and they meet, all in O(1) space.

3 variations · 6 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Find the middle of a list in one pass
  • Does the list (or a sequence like n -> next(n)) loop forever?
  • Where does the cycle start, or which value repeats?
  • O(1) extra space, so no hash set of visited nodes

The template

Slow Fast Pointers
// middle node (the second middle for an even length)
ListNode middleNode(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

// start of the cycle, or null if there is none (Floyd)
ListNode detectCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) {                       // they met inside the cycle
            ListNode p = head;                    // head and meeting point are equally far from the start
            while (p != slow) { p = p.next; slow = slow.next; }
            return p;
        }
    }
    return null;
}

The variations

  1. 1Find the middle

    Fast moves two steps, slow moves one; when fast runs out, slow is halfway. To reorder a list, find the middle, reverse the second half, then weave the two halves together.

    Now you solve
  2. 2Is there a cycle?

    In a cycle the fast pointer gains one step per move, so it must land on the slow one. The "list" can be any function: for a happy number, the next value is the sum of the squares of the digits.

    Now you solve
  3. 3Where does the cycle start?

    After they meet, start a new pointer at the head and move it and slow one step at a time: they meet at the cycle start. In an array of values 1..n, treat i -> nums[i] as a next pointer; the repeated value is the cycle start.

Mistakes to avoid

  • Testing fast.next before fast, which crashes on an even-length list.
  • Checking slow == fast before moving them: they both start at the head, so they "meet" at once.
  • Needing the first middle (to split a list in half): start fast at head.next instead.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.