Skip to lesson

Fast and slow pointers

On linked lists, you cannot index head[n / 2] or walk backward. Advancing slow by 1 and fast by 2 unlocks one-pass middle finding, cycle detection, and palindrome checks.

Middle node in one pass

Fast and slow pointers move through a linked list at different speeds, one step and two steps, to find the middle or detect a cycle in O(n) time and O(1) space.

A two-pass method counts the length n first and then walks n / 2 steps. With fast and slow pointers, we find the middle in a single pass. Because fast moves twice as fast as slow, slow reaches the middle when fast reaches the end.

Finding the middle of 1 -> 2 -> 3 -> 4 -> 5

Step 1 of 4

1slow, fast2345
slow
1
fast
1
Both pointers start at the head (node 1). The loop runs while fast and fast.next are not null.

Example 1 · Finding Both Second Middle and First Middle in One Pass (O(n) time, O(1) space)

MiddleNodeDemo.javaJava
public class MiddleNodeDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node middleNodeSecond(Node head) {        Node slow = head, fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        return slow;    }
    public static Node middleNodeFirst(Node head) {        if (head == null) return null;        Node slow = head, fast = head.next;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        return slow;    }
    public static void main(String[] args) {        Node odd = new Node(10, new Node(20, new Node(30, new Node(40, new Node(50, null)))));        Node even = new Node(10, new Node(20, new Node(30, new Node(40, null))));
        System.out.println("Odd [10..50] middle: " + middleNodeSecond(odd).val);        System.out.println("Even [10..40] 2nd middle: " + middleNodeSecond(even).val);        System.out.println("Even [10..40] 1st middle: " + middleNodeFirst(even).val);    }}
Output
Odd [10..50] middle: 30
Even [10..40] 2nd middle: 30
Even [10..40] 1st middle: 20

What this code does

  • On an odd-length list (5 nodes), both versions return the unique center node (30).
  • On 4 nodes, fast = head returns the second middle (30), and fast = head.next returns the first (20).

For an even-length list (1 -> 2 -> 3 -> 4 -> null), there are two middle nodes. Starting fast = head lands slow on the second middle (3, index n / 2). Starting fast = head.next lands slow on the first middle (2, index (n - 1) / 2).

Predict the output

Where does slow stop?

Read the code and pick what it prints.

Round 1 of 3

The list is 1 -> 2 -> 3 -> 4 -> 5.

Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
System.out.println(slow.val);

Cycle detection with Floyd's method and finding the start of the cycle

What if the last node's .next pointer points back to an earlier node? A simple while (curr != null) loop will spin forever. Floyd's Tortoise and Hare algorithm detects cycles in O(1) space.

  1. Phase 1: Advance slow by 1 and fast by 2 until slow == fast (or fast hits null).
  2. Phase 2: Set p1 = head and keep p2 = slow at the meeting point.
  3. Advance both p1 and p2 by 1 step at a time (p1 = p1.next; p2 = p2.next;) until p1 == p2.
  4. Return p1 as the exact start of the cycle.

Floyd's Cycle Detection on 1 -> 2 -> 3 -> 4 -> 5 -> 2

Step 1 of 6

1slow,fast2345
step
0
slow
1
fast
1
Start both slow and fast at head (node 1). Node 5's next pointer loops back to node 2.

Example 2 · Brute force: remember every visited node in a HashSet (O(n) time, O(n) extra space)

CycleHashSetDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class CycleHashSetDemo {    static class Node {        int val;        Node next;        Node(int val) { this.val = val; }    }
    static boolean hasCycle(Node head) {        Set<Node> seen = new HashSet<>();        for (Node curr = head; curr != null; curr = curr.next) {            if (!seen.add(curr)) return true;        }        return false;    }
    public static void main(String[] args) {        Node a = new Node(3), b = new Node(2), c = new Node(0), d = new Node(-4);        a.next = b;        b.next = c;        c.next = d;        System.out.println("No cycle:   " + hasCycle(a));        d.next = b;        System.out.println("With cycle: " + hasCycle(a));    }}
Output
No cycle:   false
With cycle: true

What this code does

  • seen.add(curr) returns false when the same node object was already stored, so the first repeated node proves a cycle.
  • Every node is visited at most once, so time is O(n), but the set grows to hold up to n nodes: O(n) extra space.
  • Floyd's method in the next example finds the same answer with only two pointers, O(1) extra space.

Example 3 · Optimal: Floyd's cycle detection and cycle entrance (O(n) time, O(1) space)

FloydCycleDemo.javaJava
public class FloydCycleDemo {    static class Node {        int val;        Node next;        Node(int val) { this.val = val; }    }
    public static Node detectCycleStart(Node head) {        Node slow = head, fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;            if (slow == fast) {                Node p1 = head;                Node p2 = slow;                while (p1 != p2) {                    p1 = p1.next;                    p2 = p2.next;                }                return p1;            }        }        return null;    }
    public static void main(String[] args) {        Node n0 = new Node(3);        Node n1 = new Node(2);        Node n2 = new Node(0);        Node n3 = new Node(-4);        n0.next = n1;        n1.next = n2;        n2.next = n3;        n3.next = n1;
        Node entrance = detectCycleStart(n0);        System.out.println("Cycle entrance value: " + (entrance != null ? entrance.val : "null"));
        n3.next = null;        System.out.println("After breaking cycle: " + detectCycleStart(n0));    }}
Output
Cycle entrance value: 2
After breaking cycle: null

What this code does

  • We compare node references using slow == fast and p1 != p2 (not .val), because distinct nodes can hold equal .val values.
  • Once slow == fast, walking p1 from head and p2 from the meeting point meets at n1 (val = 2).

Advance slow = slow.next and fast = fast.next.next while fast != null && fast.next != null. Inside a cycle of length C, the gap shrinks by 1 step per turn, so fast == slow. To find where the cycle starts, let L be the distance from head to the entrance. When they meet at offset X, slow walked L + X and fast walked L + X + kC. Thus L = kC - X, so walking L steps from head and X reaches the entrance!

Palindrome linked list in O(1) space

How can we check if 1 -> 2 -> 3 -> 2 -> 1 is a palindrome in O(1) space?

  1. Find the first half end: Use slow = head and fast = head.next to stop at the first middle.
  2. Reverse the second half in place: Call Node secondHalf = reverse(slow.next);.
  3. Compare the two halves: Walk p1 = head and p2 = secondHalf together while p2 != null, checking p1.val == p2.val.
  4. Restore the list: Reverse secondHalf again and re-attach slow.next so the caller's list is unchanged.

Example 4 · Brute force: copy the values to an ArrayList and compare from both ends (O(n) time, O(n) extra space)

PalindromeCopyDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PalindromeCopyDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    static boolean isPalindrome(Node head) {        List<Integer> values = new ArrayList<>();        for (Node curr = head; curr != null; curr = curr.next) {            values.add(curr.val);        }        int left = 0, right = values.size() - 1;        while (left < right) {            if (!values.get(left++).equals(values.get(right--))) return false;        }        return true;    }
    public static void main(String[] args) {        Node yes = new Node(1, new Node(2, new Node(3, new Node(2, new Node(1, null)))));        Node no = new Node(1, new Node(2, new Node(3, null)));        System.out.println("1 2 3 2 1: " + isPalindrome(yes));        System.out.println("1 2 3:     " + isPalindrome(no));    }}
Output
1 2 3 2 1: true
1 2 3:     false

What this code does

  • A list cannot be read backward, so the values are copied into an ArrayList, where values.get(right) is O(1).
  • Two indexes left and right walk inward and compare. Time is O(n), but the copy needs O(n) extra space.
  • The next example reverses only the second half of the list in place, so no copy is needed.

Example 5 · Optimal: reverse the second half in place (O(n) time, O(1) space, list restored)

PalindromeListDemo.javaJava
public class PalindromeListDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    static Node reverse(Node head) {        Node prev = null, curr = head;        while (curr != null) {            Node next = curr.next;            curr.next = prev;            prev = curr;            curr = next;        }        return prev;    }
    public static boolean isPalindrome(Node head) {        if (head == null || head.next == null) return true;        Node slow = head, fast = head.next;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        Node secondHalfRev = reverse(slow.next);        Node p1 = head, p2 = secondHalfRev;        boolean ok = true;        while (p2 != null) {            if (p1.val != p2.val) {                ok = false;                break;            }            p1 = p1.next;            p2 = p2.next;        }        slow.next = reverse(secondHalfRev); // Restore original list!        return ok;    }
    public static void main(String[] args) {        Node a = new Node(1, new Node(2, new Node(3, new Node(2, new Node(1, null)))));        Node b = new Node(1, new Node(2, new Node(2, new Node(1, null))));        Node c = new Node(1, new Node(2, new Node(3, null)));        System.out.println("[1,2,3,2,1]: " + isPalindrome(a));        System.out.println("[1,2,2,1]:   " + isPalindrome(b));        System.out.println("[1,2,3]:     " + isPalindrome(c));    }}
Output
[1,2,3,2,1]: true
[1,2,2,1]:   true
[1,2,3]:     false

What this code does

  • slow stops at the first half end, reverse(slow.next) flips the second half, and p1 and p2 compare values.
  • Calling slow.next = reverse(secondHalfRev) before returning leaves the input list intact.

In a singly linked list, we cannot walk a right pointer backward from the tail. Instead, we combine Fast and Slow Pointers with In-Place Reversal from Lesson 4.

In an odd-length palindrome like 1 -> 2 -> 3 -> 2 -> 1, slow stops at 3 and secondHalf is 1 -> 2 -> null (length 2). The loop stops as soon as p2 == null, ignoring the middle element 3.

Next step

Check your understanding

10 quick questions