Fast and Slow Pointers
Two pointers start at the head of a linked list. One moves one node per round, the other moves two. If the list ends, the fast one reaches the end first. If the list loops, the fast one laps the slow one and they land on the same node. That single fact gives loop detection, the loop's first node, its length and the middle of a list, with no extra memory.
Two Speeds on One List
The fast and slow pointers technique walks one sequence with two pointers at different speeds. Slow takes one step per round, fast takes two. It works on anything where each item has exactly one next item: a singly linked list, or a rule like "replace n by the sum of the squares of its digits" that turns each number into the next.
Such a sequence can do only two things. It can end (a node whose next is null), or it can fall into a loop and repeat forever. The shape of a looping list looks like the Greek letter ρ: a straight tail that runs into a ring. The two speeds tell the shapes apart without storing anything. On a list that ends, fast gets there first. On a list that loops, fast can never leave the ring, so sooner or later it catches slow from behind.
It is also called the tortoise and hare algorithm, after the fable: the slow walker is the tortoise and the fast one is the hare. It belongs to the two pointers family, but the pointers do not move toward each other from two ends; they start together and move in the same direction at different rates.
- Needs only a "next" step, no indexes and no length
- Two pointers and a loop: O(1) extra memory
- Same idea for lists, arrays read as "index → value", and number sequences
Detecting a Loop
- Set slow and fast to the head
- While fast and fast.next are not null: move slow 1 node and fast 2 nodes
- If slow and fast are now the same node, there is a loop
- If the loop ends because fast or fast.next is null, the list has an end and no loop
Why must they meet, instead of fast jumping over slow forever? Once both pointers are inside the ring, look at how far fast is behind slow, counted along the ring. Each round slow moves 1 forward and fast moves 2, so that distance drops by exactly 1. A distance that drops by 1 each round must hit 0, and it cannot skip from 1 to −1. So fast lands on slow, it does not pass it.
The cost is small. Slow enters the ring after μ rounds, where μ is the length of the tail. From then on the gap is less than the ring length λ, so they meet within λ more rounds. That is at most μ + λ rounds, which is O(n) for a list of n nodes, with O(1) extra memory.
The simple alternative is a visited set: walk the list, store every node, and stop at the first node seen twice. It is just as fast and also finds the first repeated node, but it stores up to n references. Two pointers give the same answer in constant memory, which is why interviewers ask for it.
- Compare nodes (references), never values: two different nodes can hold the same number
- Check fast and fast.next before moving fast, or the second step reads past the end
- Time O(μ + λ), extra memory O(1)
Finding Where the Loop Starts
Floyd's cycle detection algorithm has a second phase that finds the first node of the ring, where the tail joins it. After the two pointers meet, move one of them back to the head. Leave the other at the meeting node. Now move both one step at a time. The node where they meet again is the start of the loop.
The reason is a short count. Say they first met k steps into the ring. Slow walked μ + k steps. Fast walked twice that, 2(μ + k), and the extra μ + k steps were whole laps of the ring. So μ + k is a multiple of λ. That means walking μ more steps from the meeting point (k into the ring) brings you to a whole number of laps, which is the ring's first node. The pointer from the head also reaches that node after exactly μ steps, so they arrive together.
The ring's length comes for free. From the meeting node, hold one pointer still and walk the other around the ring, counting steps until it is back. In the example on this page the tail has 3 nodes, the ring has 4, the pointers meet on the node holding 5, and phase two meets on the node holding 8, the ring's first node.
- Phase 2: one pointer from the head, one from the meeting node, both at speed 1
- Both speeds must be 1 in phase 2; the count relies on it
- Ring length: walk once around from the meeting node
Terms, operations, and practical uses
Key terms
- Tail (μ)The nodes before the loop; μ is how many there are.
- Ring (λ)The nodes that repeat forever; λ is the loop length.
- Meeting nodeWhere fast first lands on slow, somewhere inside the ring.
- Loop entryThe first node of the ring, found by phase two.
Related lessons and problems
- Two PointersThe wider family: converging pointers and same-direction pointers.
- Linked ListsNodes, next references and the operations these pointers walk.
- Cycle Detection in GraphsLoops when a node can have many next nodes.
- Linked List Cycle II (problem)Return the node where the loop begins.
Code in Python, C++ and Java
class Node:
def __init__(self, val):
self.val = val
self.next = None
def build(values, loop_to=-1):
nodes = [Node(v) for v in values]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if loop_to >= 0:
nodes[-1].next = nodes[loop_to]
return nodes[0] if nodes else None
def meeting_point(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return slow
return None
def cycle_start(head):
meet = meeting_point(head)
if meet is None:
return None
slow = head
while slow is not meet:
slow = slow.next
meet = meet.next
return slow
def cycle_length(head):
meet = meeting_point(head)
if meet is None:
return 0
length, node = 1, meet.next
while node is not meet:
length += 1
node = node.next
return length
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
looped = build([3, 1, 4, 8, 5, 9, 2], loop_to=3)
print("meet at", meeting_point(looped).val)
print("loop starts at", cycle_start(looped).val)
print("loop length", cycle_length(looped))
straight = build([3, 1, 4, 8, 5])
print("loop?", meeting_point(straight) is not None)
print("middle of 5 nodes", middle(straight).val)
print("middle of 6 nodes", middle(build([3, 1, 4, 8, 5, 9])).val)
solo = build([7], loop_to=0)
print("self loop starts at", cycle_start(solo).val)
print("empty list loop?", meeting_point(None) is not None)#include <iostream>
#include <vector>
using namespace std;
struct Node {
int val;
Node* next = nullptr;
Node(int v) : val(v) {}
};
Node* build(const vector<int>& values, int loopTo = -1) {
if (values.empty()) return nullptr;
vector<Node*> nodes;
for (int v : values) nodes.push_back(new Node(v));
for (size_t i = 0; i + 1 < nodes.size(); i++) nodes[i]->next = nodes[i + 1];
if (loopTo >= 0) nodes.back()->next = nodes[loopTo];
return nodes[0];
}
Node* meetingPoint(Node* head) {
Node *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return slow;
}
return nullptr;
}
Node* cycleStart(Node* head) {
Node* meet = meetingPoint(head);
if (!meet) return nullptr;
Node* slow = head;
while (slow != meet) {
slow = slow->next;
meet = meet->next;
}
return slow;
}
int cycleLength(Node* head) {
Node* meet = meetingPoint(head);
if (!meet) return 0;
int length = 1;
for (Node* node = meet->next; node != meet; node = node->next) length++;
return length;
}
Node* middle(Node* head) {
Node *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
int main() {
Node* looped = build({3, 1, 4, 8, 5, 9, 2}, 3);
cout << "meet at " << meetingPoint(looped)->val << "\n";
cout << "loop starts at " << cycleStart(looped)->val << "\n";
cout << "loop length " << cycleLength(looped) << "\n";
Node* straight = build({3, 1, 4, 8, 5});
cout << "loop? " << (meetingPoint(straight) ? "True" : "False") << "\n";
cout << "middle of 5 nodes " << middle(straight)->val << "\n";
cout << "middle of 6 nodes " << middle(build({3, 1, 4, 8, 5, 9}))->val << "\n";
Node* solo = build({7}, 0);
cout << "self loop starts at " << cycleStart(solo)->val << "\n";
cout << "empty list loop? " << (meetingPoint(nullptr) ? "True" : "False") << "\n";
}public class Main {
static class Node {
int val;
Node next;
Node(int v) { val = v; }
}
static Node build(int[] values, int loopTo) {
if (values.length == 0) return null;
Node[] nodes = new Node[values.length];
for (int i = 0; i < values.length; i++) nodes[i] = new Node(values[i]);
for (int i = 0; i + 1 < nodes.length; i++) nodes[i].next = nodes[i + 1];
if (loopTo >= 0) nodes[nodes.length - 1].next = nodes[loopTo];
return nodes[0];
}
static Node meetingPoint(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return slow;
}
return null;
}
static Node cycleStart(Node head) {
Node meet = meetingPoint(head);
if (meet == null) return null;
Node slow = head;
while (slow != meet) {
slow = slow.next;
meet = meet.next;
}
return slow;
}
static int cycleLength(Node head) {
Node meet = meetingPoint(head);
if (meet == null) return 0;
int length = 1;
for (Node node = meet.next; node != meet; node = node.next) length++;
return length;
}
static Node middle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static void main(String[] args) {
Node looped = build(new int[]{3, 1, 4, 8, 5, 9, 2}, 3);
System.out.println("meet at " + meetingPoint(looped).val);
System.out.println("loop starts at " + cycleStart(looped).val);
System.out.println("loop length " + cycleLength(looped));
Node straight = build(new int[]{3, 1, 4, 8, 5}, -1);
System.out.println("loop? " + (meetingPoint(straight) != null ? "True" : "False"));
System.out.println("middle of 5 nodes " + middle(straight).val);
System.out.println("middle of 6 nodes " + middle(build(new int[]{3, 1, 4, 8, 5, 9}, -1)).val);
Node solo = build(new int[]{7}, 0);
System.out.println("self loop starts at " + cycleStart(solo).val);
System.out.println("empty list loop? " + (meetingPoint(null) != null ? "True" : "False"));
}
}Step through it
Running on 3 → 1 → 4 → 8 → 5 → 9 → 2 → back to 8
Middle of a List and Other Uses
On a list with no loop, run the same two speeds until fast reaches the end. Slow has then walked half as far, so it stands at the middle. With 5 nodes it stops on the 3rd. With 6 nodes the loop condition while fast and fast.next stops slow on the 4th, the second of the two middle nodes; testing fast.next and fast.next.next instead stops it on the 3rd. Choose the version the problem asks for.
Finding the middle is a building block. A palindrome check on a list finds the middle, reverses the second half and compares the halves. Reordering a list as first, last, second, second-to-last does the same split, then weaves the halves together. Neither needs the length up front.
The fast and slow pointers pattern also covers sequences that are not stored lists. In the happy number problem, each number leads to the sum of the squares of its digits, and the question is whether you reach 1 or loop forever. In the duplicate number problem, the array is read as a list where index i points to index nums[i]; the repeated value is the first node of the loop. A fixed gap is a different idea: to find the k-th node from the end, move one pointer k nodes ahead, then move both at the same speed.
- Middle: stop when fast or fast.next is null; slow is the middle
- Palindrome and reorder problems: find the middle, reverse the second half
- Any "each item has one next" rule can be checked for a loop the same way
Mistakes That Break It
Moving fast without checking. fast = fast.next.next on the last node reads the next of null and crashes. The loop test must check both fast and fast.next.
Different speeds in phase two. If fast keeps moving 2 steps while the other pointer walks from the head, the count no longer holds. On this page's list they meet again on the node holding 5, not on the ring's first node, and the answer is wrong.
Starting fast one node ahead. Some code sets fast = head.next so the loop test can be while slow != fast. Detection still works, but the meeting point shifts by one, and the phase two count breaks unless you adjust for it. Start both at the head unless you have a reason not to.
- Test an empty list, a single node, and a node whose next is itself
- Test an even and an odd length for the middle
- Print the node values, not the references, when you debug
Practice and Next Steps
These problems use the two speeds directly. Do the first three in order; the last two need the idea applied to something that is not a stored list.
For loops in graphs with many edges per node, where each node has more than one next, two pointers no longer apply; use the depth-first search methods in cycle detection.
- Linked List Cycle: phase one only
- Linked List Cycle II: add phase two to return the first node of the loop
- Middle of the Linked List: stop when fast runs out
- Happy Number: the sequence of digit-square sums either reaches 1 or loops
- Find the Duplicate Number: read the array as index → value and find the loop's start