Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Linked Lists/Fast & Slow Pointers

Learn the pattern · ~16 min

Fast & Slow Pointers

also called Floyd's tortoise and hare, cycle detection

Send two pointers down the same chain, one at double speed: on a straight chain the fast one falls off the end; in a loop it must catch the slow one, and a second walk from the head finds where the loop starts.

Signalslinked list cycle or middlea sequence x -> f(x) that must eventually repeat (happy number)array values used as next-pointers with O(1) space
Cheat sheet and practice

Reach for it when you read

  • +Does a linked list loop, and where does the loop start? With O(1) extra memory.
  • +The middle of a linked list in one pass, often as the first step of a split or a palindrome check.
  • +The n-th node from the end in one pass: two pointers a fixed gap apart.
  • +A sequence where each value decides the next (x → f(x), i → nums[i]) and you must detect that it repeats.

Not this one when

  • ×Two indices closing in from both ends of a sorted array to hit a sum: that's opposite-end two pointers, not two speeds.
  • ×Detecting a cycle in a general graph with many edges per node: DFS with colours, or topological sort.

Learn Fast & Slow Pointers

First, what are fast and slow pointers?

In a linked list each node has one arrow, next, to the next node, and the last one points to null. Unless there's a cycle: a node points back to an earlier one, and following next goes round forever.

Fast and slow pointers walk the same list at two speeds: slow moves one node per step, fast moves two. After 3 steps, slow is 3 nodes from the start and fast is 6. fast is always exactly twice as far.

How do two speeds find the middle?

Take 1 → 2 → 3 → 4 → 5 → 6 → 7. Both pointers start on node 1. The rule:

Each step, slow moves one node and fast moves two. Stop when fast can't move two.

step what happens slow fast
start both on the head 1 1
1 slow 1 → 2, fast 1 → 3 2 3
2 slow 2 → 3, fast 3 → 5 3 5
3 slow 3 → 4, fast 5 → 7 4 7
stop fast is on the last node: no two moves left 4 7

fast walked twice as far as slow and reached the end, so slow is halfway: node 4. With six nodes, fast goes 1, 3, 5, then off the end, and slow stops on 4, the second of the two middles.

The code for it

C++
ListNode *slow = head, *fast = head;
while (fast && fast->next) {      // fast needs two nodes ahead to jump
    slow = slow->next;
    fast = fast->next->next;
}
// slow is the middle

You don't need to memorise this. It's the table: move one, move two, stop when two moves aren't possible.

Why check both fast and fast->next? With an odd length, fast lands on the last node and fast->next->next would read through null. With an even length, fast itself becomes null.

Fine, but how does this help us?

The classic: Linked List Cycle II. Return the node where the cycle starts, or null if there's no cycle. The follow-up asks for O(1) extra memory.

Take 1 → 2 → 3 → 4 → 5 → 6, where 6 points back to 3. Walk it by hand, noting every node:

step node seen before?
0 1 no
1 2 no
2 3 no
3 4 no
4 5 no
5 6 no
6 3 yes: 6's arrow brought us back

The first node you visit twice is where the cycle starts: 3.

The brute force

A hash set of visited nodes is O(n) time, but also O(n) memory. Without a set, check each new node against every earlier one by walking from the head again:

C++
ListNode* bruteStart(ListNode* head) {
    ListNode* cur = head;
    for (int i = 0; cur; i++, cur = cur->next) {
        ListNode* p = head;
        for (int j = 0; j < i; j++, p = p->next)
            if (p == cur) return cur;     // visited before: the cycle starts here
    }
    return nullptr;                       // reached the end: no cycle
}

That's about n²/2 pointer steps. LeetCode caps this list at 10⁴ nodes: 5 × 10⁷ steps, about 0.04 s, so it passes. But at 10⁵ nodes it's 5 × 10⁹ steps, and it took 4.6 s.

The one thought that fixes it

In a cycle fast never falls off. So do they meet, and what does the meeting tell us?

Do they meet? Stop at step 2: slow has just entered the cycle at 3, and fast is on 5. The cycle is 3 → 4 → 5 → 6, four nodes, and going round fast is 2 behind slow (5 → 6 → 3). fast gains one node per step, so the gap shrinks by exactly one: 2, 1, 0. It can't skip zero, so they meet within one lap: at step 4, on node 5.

Where's the entrance? Call a the steps from the head to the entrance: here a = 2 (1 → 2 → 3). They met after 4 steps: slow walked 4, fast 8.

  • fast walked 4 more steps than slow and ended on the same node. Steps that return you to the same node are whole laps: here 4 is one lap.
  • Move slow a more steps. That's a + 4 from the head: a steps reach the entrance, and 4 more are whole laps back to it. So slow stands on the entrance.
  • A new pointer p that starts at the head also reaches the entrance after a steps. That's what a means.
  • They can't meet earlier: until then p is on the tail, outside the cycle, and slow never leaves the cycle.

So put p on the head and move p and slow one step at a time: they meet at the entrance. Nothing used the numbers 2 or 4: for any list, the steps until the meeting are whole laps.

It's the middle-finding loop from the start, plus one check (slow == fast) and a second walk.

C++
ListNode* cycleStart(ListNode* head) {
    ListNode *slow = head, *fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) {                  // compare nodes, not values
            ListNode* p = head;
            while (p != slow) { p = p->next; slow = slow->next; }   // both one step
            return p;                        // the entrance
        }
    }
    return nullptr;                          // fast fell off: no cycle
}

Dry run

Same list, 6 pointing back to 3.

phase step what happens slow fast / p
1 1 slow 1 → 2, fast 1 → 3 2 fast 3
1 2 slow enters the cycle, fast is 2 behind 3 fast 5
1 3 slow 3 → 4, fast 5 → 6 → 3: gap 1 4 fast 3
1 4 slow 4 → 5, fast 3 → 4 → 5: gap 0, they meet 5 fast 5
2 1 p starts on the head; both move one 6 p 2
2 2 both move one: same node 3 p 3

The cycle starts at 3, the same answer as the brute force.

Why it's O(n)

Count slow's steps: a to reach the cycle, then fewer than L (the cycle's length) until the gap closes. Since a + L ≤ n, slow walks at most n steps, fast 2n, and phase two adds a: O(n) time. A few pointers: O(1) space.

From O(n²) time (or O(n) memory) down to O(n) time and O(1) memory, by letting a faster pointer catch a slower one.

The first middle? Start fast one ahead

Splitting a list for merge sort wants the first middle. Start fast one node ahead:

C++
ListNode *slow = head, *fast = head->next;

On 1 → … → 6, slow now stops on 3; on seven nodes, still 4.

n-th from the end? A fixed gap, not double speed

Same speed, but fast gets a head start of n nodes. When it falls off the end, slow is n nodes behind.

C++
ListNode *slow = head, *fast = head;
for (int i = 0; i < n; i++) fast = fast->next;   // the gap
while (fast) { slow = slow->next; fast = fast->next; }
// slow is the n-th node from the end

On 1 → … → 7 with n = 2, fast starts on 3 and slow stops on 6. To delete it, start both on a dummy node before the head and loop while (fast->next): slow stops one node earlier, on 5.

No list at all? A chain of numbers

next can be any rule where each value decides the next. In Happy Number it's the sum of the squares of the digits: 19 → 82 → 68 → 100 → 1 reaches 1, but 2 → 4 → 16 → … → 42 → 20 → 4 cycles. Use slow = f(slow), fast = f(f(fast)).

In Find the Duplicate Number, next(i) = nums[i]. For [1, 3, 4, 2, 2]: 0 → 1 → 3 → 2 → 4 → 2 → … Indices 3 and 4 both point at 2, so the cycle starts at 2, the duplicate, and the same two phases find it.

Remember this

  • Two speeds find the middle and the cycle; a fixed gap finds the n-th from the end.
  • Check fast && fast->next before jumping two.
  • To find the entrance, restart one pointer at the head and move both one step. It works because the steps until the meeting are whole laps.
  • Compare nodes (slow == fast), not values: two nodes can hold the same value.
  • Whenever a problem asks for a cycle, the middle or the n-th from the end in O(1) memory, or a sequence where each value decides the next, it's fast and slow pointers.

Practise it on Middle of the Linked List, then Linked List Cycle (stop at the meeting), Linked List Cycle II (the entrance), Happy Number (a chain of numbers), Remove Nth Node From End of List (a fixed gap) and Find the Duplicate Number (an array as pointers).

Below, watch Linked List Cycle II run line by line.

Watch it work, line by line

Linked List Cycle II ↗, 1 → 2 → 3 → 4 → 5 → 6 → back to 3 → 3. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is there a chain where every item has exactly one next (a list, or x → f(x)), and do I need a loop, its start or the middle without extra memory?

Reach for it when

  • +linked list cycle or middle
  • +a sequence x -> f(x) that must eventually repeat (happy number)
  • +array values used as next-pointers with O(1) space
  • +O(1) extra space required

It fails when

  • ×A hash set is affordable and you want simpler codeuse Visited set
  • ×You have random access (array) and want the middleuse Index len // 2
  • ×Nodes have several successors, or you need the cycle members of a general graphuse DFS with colouring

Looks like it, isn't (and the other way round)

  • Find the Duplicate Number looks like Cyclic Sort, needs this pattern

    Array must not be modified and O(1) space: values form a functional graph whose cycle entry is the duplicate.

  • Happy Number looks like Math / Number Theory, needs this pattern

    The question is whether an iterated function cycles; Floyd detects it without a set.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why can't fast jump over slow inside the loop?Reveal

    Each step fast gains exactly one node on slow, so the gap goes ..., 2, 1, 0. It can't skip from 1 to −1.

  • 2Is the meeting point the start of the cycle?Reveal

    No. Restart one pointer at the head and move both one step at a time; they meet at the start.

  • 3What's the loop guard, and why both parts?Reveal

    while (fast && fast->next). fast takes two steps, so both fast and fast->next must exist.

Practice ladder

every problem →
  1. 1Middle of the Linked Listthe middleEasy
  2. 2Linked List Cycleis there a loopEasy
  3. 3Linked List Cycle IIthe hookMedium
  4. 4Happy Numbernumber chainEasy
  5. 5Remove Nth Node From End of Listfixed gapMedium
  6. 6Palindrome Linked Listmiddle, then reverseEasy
  7. 7Reorder Listmiddle, then reverseMedium
  8. 8Find the Duplicate Numberarray as pointersMedium
  9. 9Sort Listsplit for merge sortMedium

Finished Fast & Slow Pointers? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Fast & Slow Pointers

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial