Home › DSA Patterns › Fast and Slow Pointers
F

Fast and Slow Pointers

Learn this one pattern well and a whole family of linked-list and sequence problems turns from scary into mechanical. Interviewers love it because it looks clever but has a tiny, memorizable core: two pointers, maybe eight lines of code. Once you see the trick, you cannot unsee it. I have watched this exact pattern decide a phone screen, because the hash-set answer gets you partial credit and the Floyd answer gets you the callback.

DSA PatternsMedium10 min read
Who asks this, and how oftenInterview frequency: Common

Most asked at Amazon. Here is how often this pattern shows up in each company's coding rounds.

Amazon
80
Microsoft
78
Meta
70
Google
66
Apple
64
Relative frequency index from 0 to 100, based on commonly reported interview experiences. Use it as a guide to where this pattern pays off most, not an exact count.

If you remember five things

The recognition cues, the template, and the complexity in one glance. Everything below defends these five.

  1. Two speeds, read the gap. One pointer moves one step, the other moves two. On a loop the gap shrinks by one per step until they collide, which proves a cycle exists.
  2. The trigger words. Linked list plus O(1) space, the word "cycle," "the middle in one pass," or "Nth from the end." Any of those should light this pattern up.
  3. Guard before you deref. Loop while fast != null AND fast.next != null, in that order, and compare pointers after moving, never before.
  4. Two phases for the loop start. Phase one finds a meeting point. Phase two resets one pointer to head and walks both at equal speed until they collide at the entrance.
  5. O(n) time, O(1) space. That constant space is the entire selling point over the hash-set answer, which costs O(n) space for the same time.

1The mental model (what this really is)#

Picture two runners on the same track. One jogs, one sprints, and the sprinter moves two steps for every one step the jogger takes. Ask a few questions about those runners and you basically have the whole pattern.

Straight-line track: the midpoint falls out for free.

  • The sprinter reaches the end first.
  • When the sprinter is at the end, the jogger is exactly halfway.
  • That is the midpoint trick, and it works because the sprinter covered twice the distance in the same number of moves.

Looping track: the collision proves a cycle.

  • If the end secretly connects back to somewhere earlier, the sprinter can never escape and keeps circling.
  • The jogger is stuck on the same loop, just slower.
  • The sprinter closes the gap by exactly one node per move, so he eventually laps the jogger and they land on the same spot.
  • That collision is proof a cycle exists. This is Floyd's cycle detection (the tortoise and hare), which dates to the 1960s and has been an interview staple ever since.

The core insight.

  • When two things move through the same structure at different speeds, the gap between them changes in a predictable way.
  • On a straight line the gap grows. On a loop the gap shrinks by one each step until it hits zero.
  • You exploit that gap: sometimes it tells you a cycle exists, sometimes where the middle is, sometimes the Nth element from the end.

Two pointers, different speeds, read the gap. That is the entire pattern.

2How to recognize it (the signals in a problem)#

You rarely get a problem that says "use fast and slow pointers." You have to smell it. These are the tells I look for.

  • Linked list and you want O(1) extra space. The second someone says "don't use a hash set" or "constant space," your hash-set instinct is dead and this pattern should light up. The hash-set solution is O(n) space, this one is O(1), and that gap is the whole point of the follow-up.
  • The word "cycle" appears. Detect a cycle, find where it starts, measure its length. All Floyd.
  • You need the middle of a list in one pass. You cannot index into a linked list, and the two-pass fix (walk once for length n, walk n/2 again) touches nodes twice. Fast and slow finds the middle in a single traversal.
  • "Nth from the end." One pointer gets an N-step head start, then both move together. When the leader hits the end, the follower sits exactly N nodes back, on the answer.
  • A sequence where each value points to a next index and you are asked if it loops. Think "keep squaring digits" or "jump by array value." That hidden chain is a linked list in disguise, and a disguised linked list means Floyd works.
The pro move

The structure does not have to be an actual linked list. If each state has exactly one deterministic next state, you have an implicit linked list and this pattern applies. Find the Duplicate Number is the classic trap: an array of n+1 numbers in range 1..n, treated as index-to-index links, must contain a cycle. Saying that sentence out loud shows you understand the pattern instead of memorizing it.

3The template (how it works, with pseudocode)#

Here is the cycle-detection skeleton. Memorize this shape. Everything else is a variation on it.

function hasCycle(head):
    slow = head
    fast = head

    while fast is not null and fast.next is not null:
        slow = slow.next          # move 1 step
        fast = fast.next.next     # move 2 steps
        if slow == fast:          # they met -> cycle
            return true

    return false                  # fast fell off the end -> no cycle

Two things people get wrong here, and both cost you.

  • The loop condition is fast != null AND fast.next != null. You check fast.next because the very next line calls fast.next.next. Skip it and you throw a null-pointer exception on an even-length list, because fast lands on the last node and fast.next is null.
  • Order matters. Test fast != null first, since the second clause dereferences fast.
  • Compare after moving, not before. Start both at head and compare first and they are trivially equal, so you falsely report a cycle on step zero.
Red flag that costs you the round

Not guarding fast.next before fast.next.next. It throws on even-length and empty lists, and it is the single most common crash I see on this pattern. An interviewer who watches you write fast.next.next with no guard above it has already made a note.

The middle variant is the same shape, minus the equality check.

function middle(head):
    slow = head
    fast = head
    while fast is not null and fast.next is not null:
        slow = slow.next
        fast = fast.next.next
    return slow                   # slow is at the midpoint
  • For a list of length 6, this returns node 4 (the second of the two middles).
  • Starting fast = head.next instead returns node 3, the first middle.
  • Pick your convention before you write a line.

4A worked example (walk through one problem step by step)#

Let's do the hardest of the easy ones: not just "is there a cycle" but where does the cycle start? This is Linked List Cycle II, a Medium that shows up far more than its rating suggests, and it separates people who memorized the template from people who understand it.

The list is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 3, where node 6 points back to node 3. So the tail 3,4,5,6 is a loop and node 3 is where the loop begins.

Pause before you read on: you run the standard template and the pointers collide at some node inside the loop. Is that meeting node the start of the loop? If not, how far off is it?
Reveal the answer
No. The meeting point is somewhere inside the loop, almost never the entrance. Phase one only proves a cycle exists and hands you a collision node. You still need phase two: reset one pointer to the head, walk both at equal speed, and the spot where they meet is the true loop start. In this example they collide at node 5, but the loop begins at node 3.

Phase 1: find a meeting point.

Run the standard template. Slow moves one, fast moves two.

  • Start: slow=1, fast=1
  • Step: slow=2, fast=3
  • Step: slow=3, fast=5
  • Step: slow=4, fast=3 (fast went 5 -> 6 -> 3)
  • Step: slow=5, fast=5

They meet at node 5 after four moves. We know there is a cycle, but node 5 is not the loop start. The start is node 3, so we are not done.

Phase 2: find the start.

Reset one pointer to the head, leave the other at the meeting point, then move both one step at a time at the same speed. Where they meet is the loop start.

  • slow=1 (reset to head), fast=5 (stays at meeting point)
  • Step: slow=2, fast=6
  • Step: slow=3, fast=3

They meet at node 3 after two moves. That is the answer.

Why this works (the one-sentence intuition).

  • Call the distance from head to the loop start a (here a=2, node 1 to node 3).
  • Call the distance from the loop start to the meeting point b (here b=2, node 3 to node 5).
  • When they met, slow had walked a + b, and fast walked exactly twice that, so the extra distance fast covered is a whole number of loop laps.
  • Work that out and a equals the distance from the meeting point back around to the loop start.
  • So a pointer from head and a pointer from the meeting point, both moving one step, cover a at the same moment and collide right at the entrance.
From the interviewer's chair

You do not need to reproduce the algebra at the whiteboard. You do need to say the sentence: "a equals the distance from the meeting point back to the start, so a head reset plus an equal-speed walk lands both on the entrance." Candidates who can explain the why, not just recite the two phases, are the ones I pass.

The takeaway: phase one proves a cycle and gives a meeting point, phase two converts that meeting point into the loop entrance with a head reset and an equal-speed walk.

5Variations and gotchas#

The template barely changes across these. What changes is where you start the pointers and what you do when the walk ends.

  • Middle of a list. One pointer double-speed, return slow at the end. For even length, decide up front whether you want the first or second middle. Starting fast at head versus head.next shifts which one you land on, and interviewers do ask "which middle?"
  • Nth node from the end. This is a fixed-gap two-pointer, not a speed difference. Advance one pointer N steps first, then move both at the same speed. When the leader hits null, the follower is on the Nth-from-end. To remove it, stop the follower one node early and use a dummy node before head so you can delete the very first node cleanly.
  • Palindrome linked list. Find the middle with fast and slow, reverse the second half in place, then compare halves node by node. Clean O(1) space. It is a favorite because it chains two patterns, and it is where most people fumble the pointer reversal under pressure.
  • Happy number and implicit chains. No real list exists. The "next" is sum of squares of digits. Run slow and fast over that function. Meet at 1 means happy, meet anywhere else means a cycle that never reaches 1. Same template, the pointer is just an integer and .next is a function call.
  • Cycle length. Once slow and fast meet, keep one still and walk the other around until it returns, counting steps. That count is the loop length. In the section 4 example it would be 4, the nodes 3,4,5,6.
Easy to forget, and it reads as careless

Fast and slow gives O(1) space, but it does not preserve the original structure if you reverse part of it (the palindrome case). If the interviewer wants the list intact afterward, reverse the second half back before you return, and say so out loud. That kind of care separates a hire from a maybe.

6Complexity#

Time is O(n).

  • The slow pointer visits each node at most a constant number of times.
  • In cycle detection, once both pointers are inside the loop, fast closes the gap by one node per step and catches slow within one loop traversal.
  • Total work is at most about 2n pointer moves, still linear even though fast moves twice as fast.

Space is O(1), and that is the entire selling point.

  • The naive alternative stores every visited node in a hash set and checks for repeats.
  • That is also O(n) time but costs O(n) space.
  • When an interviewer pushes you from the hash-set answer to "can you do better on space," fast and slow is the better they want.
O(1)
The number that wins the follow-upExtra space for Floyd versus O(n) for the hash set, at the same O(n) time. This single gap is why the pattern exists and why the interviewer asks you to improve on the set.
How to sequence it in the room

If you only know the hash-set solution, say it first (it is correct and easy to reason about), then say "I can get this to constant space with Floyd's" and write the template. Naming both and stating the tradeoff reads as senior. Jumping straight to Floyd with no mention of the simpler option can read as rehearsed.

7Mistakes that cost people the round#

  • Null-check sloppiness. Not guarding fast.next before fast.next.next. Throws on even-length and empty lists. The most common crash on this pattern.
  • Comparing before moving. Returns a false-positive cycle on step zero. Move first, then compare.
  • Forgetting phase two exists. Candidates find the meeting point and declare victory when the question asked for the loop start. Read the prompt. Meeting point and loop start are different nodes, node 5 versus node 3 in our example.
  • Jumping to the answer with no reasoning. Interviewers have seen the template a thousand times. Say why the two speeds collide (the gap shrinks by one each step inside the loop) or why the head reset finds the entrance (a equals meeting-point-to-start). That one sentence gets you the hire.
  • Not handling a single node or empty list. head is null, or head.next is null. State these two cases out loud before you code. It takes five seconds and signals care.
  • Reaching for a hash set when they explicitly banned extra space. You would be shocked how often panic wins and someone grabs the set anyway.

8Your practice path (named problems by difficulty)#

Do them in this order. Do not skip the easy ones, they build the muscle memory that makes the hard ones feel routine. Target roughly 25 to 30 minutes each, and re-solve any one you needed a hint on a day later from scratch.

Warm up (Easy):

  • Linked List Cycle (the bare hasCycle template)
  • Middle of the Linked List (midpoint, pick your convention)
  • Happy Number (first implicit-chain problem)
  • Palindrome Linked List (middle plus reverse-in-place)

Core (Medium):

  • Linked List Cycle II (find the start, the one from section 4)
  • Remove Nth Node From End of List (fixed-gap, use a dummy head)
  • Find the Duplicate Number (the sneaky array-as-linked-list version)
  • Reorder List (middle, reverse, then merge two halves)
  • Sort List (uses the middle-finding step to split for merge sort)

Stretch (Hard-ish):

  • Rotate List (fixed-gap thinking plus wraparound)
  • Circular Array Loop (implicit chain with direction and self-loop edge cases)

When you can do Find the Duplicate Number and explain why an array of numbers is secretly a linked list, you own this pattern. That one is the litmus test, everything else is a warm-up for it.

9Where this shows up#

  • A staple of phone screens and the first onsite coding round almost everywhere.
  • A rite of passage at the big product companies, and constant at fast-moving startups that pull from the classic question bank.
  • Expect at least one linked-list or cycle question in any round that lists "data structures" on the rubric.
  • Low-risk, high-signal for them: cheap to pose, solvable in 20 minutes, and it cleanly separates people who understand pointer mechanics from people who only memorized sorting.
  • Linked List Cycle and its "find the start" sequel, plus Find the Duplicate Number, are among the most-repeated single-topic questions in the whole screening bank.
Follow-ups the interviewer will ask (and your answers)
"You found where they meet. Now give me where the cycle actually starts."
Phase two. Reset one pointer to the head, leave the other at the meeting point, and walk both one step at a time. The distance from head to the start equals the distance from the meeting point around to the start, so they collide exactly at the loop entrance. In the section 4 list they meet at node 3, the true start.
"Can you do this without the extra hash set, in constant space?"
Yes, that is the whole point of Floyd's. The hash-set answer is O(n) time and O(n) space. Fast and slow keeps O(n) time and drops to O(1) space by using the collision of two different-speed pointers instead of remembering every node I visited.
"This is an array of integers, not a linked list. Does the pattern still apply?"
If each value points to exactly one next index, it is an implicit linked list and Floyd works unchanged. Find the Duplicate Number is the classic case: n+1 numbers in range 1..n, read as index-to-index links, must form a cycle, and the cycle entrance is the duplicate. The pointer is just an index and `.next` is `nums[i]`.
"Give me the middle node in one pass. Which middle do you return on even length?"
Fast moves two, slow moves one, return slow when fast falls off the end. Starting fast at head returns the second of the two middles, starting fast at head.next returns the first. I state my convention before writing, since on even-length lists the two differ by one node.
"How would you measure the length of the cycle?"
After slow and fast meet, freeze one pointer and walk the other around the loop one step at a time until it returns to the frozen node, counting steps. That count is the cycle length. No extra space, one more partial traversal.

What you can now explain in the room

  • Why two pointers at different speeds collide inside a loop but never on a straight line.
  • Why the loop condition guards `fast.next` before dereferencing `fast.next.next`.
  • How phase two converts a meeting point into the exact loop entrance, and the one-sentence reason it works.
  • Why Floyd's is O(n) time and O(1) space, and how that beats the hash-set answer.
  • How "Nth from the end" uses a fixed gap rather than a speed difference.
  • Why an array of index-to-index values is secretly a linked list, making Find the Duplicate Number a Floyd problem.

Want to know which companies lean on linked-list and pointer questions in which rounds? Check the company guides to see where this pattern tends to appear.

Get a prep plan built around your Fast and Slow Pointers interview

Tell us the role and your interview date. We will send back a dated, day by day plan. Free.

Thanks. Check your inbox, your Fast and Slow Pointers prep plan is on the way.