Fast and slow pointers
34 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
- slow
- 1
- fast
- 1
Example 1 · Finding Both Second Middle and First Middle in One Pass (O(n) time, O(1) space)
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); }}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 (
5nodes), both versions return the unique center node (30). - On 4 nodes,
fast = headreturns the second middle (30), andfast = head.nextreturns 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.
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.
- Phase 1: Advance
slowby 1 andfastby 2 untilslow == fast(orfasthitsnull). - Phase 2: Set
p1 = headand keepp2 = slowat the meeting point. - Advance both
p1andp2by 1 step at a time (p1 = p1.next; p2 = p2.next;) untilp1 == p2. - Return
p1as the exact start of the cycle.
Floyd's Cycle Detection on 1 -> 2 -> 3 -> 4 -> 5 -> 2
Step 1 of 6
- step
- 0
- slow
- 1
- fast
- 1
Example 2 · Brute force: remember every visited node in a HashSet (O(n) time, O(n) extra space)
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)); }}No cycle: false With cycle: true
What this code does
seen.add(curr)returnsfalsewhen 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)
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)); }}Cycle entrance value: 2 After breaking cycle: null
What this code does
- We compare node references using
slow == fastandp1 != p2(not.val), because distinct nodes can hold equal.valvalues. - Once
slow == fast, walkingp1fromheadandp2from the meeting point meets atn1(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?
- Find the first half end: Use
slow = headandfast = head.nextto stop at the first middle. - Reverse the second half in place: Call
Node secondHalf = reverse(slow.next);. - Compare the two halves: Walk
p1 = headandp2 = secondHalftogether whilep2 != null, checkingp1.val == p2.val. - Restore the list: Reverse
secondHalfagain and re-attachslow.nextso 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)
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)); }}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, wherevalues.get(right)is O(1). - Two indexes
leftandrightwalk 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)
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)); }}[1,2,3,2,1]: true [1,2,2,1]: true [1,2,3]: false
What this code does
slowstops at the first half end,reverse(slow.next)flips the second half, andp1andp2compare 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.
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