Skip to content
DSA in JavaScript
← All patterns

Fast & Slow Pointers

0/13 solved

What it is

Two pointers walk a linked list at different speeds. If there is a loop the fast one catches the slow one, and when the fast one hits the end the slow one is in the middle.

Used for

Cycle detection, finding the middle, the start of a cycle, the kth node from the end.
1slow, fast
→
2
→
3
→
4
→
5
↩ tail points to node 3

both start at node 1

Step 1 of 6

Question: does this chain of nodes loop back on itself? Walking it one node at a time never answers that, because inside a loop you just keep going. Instead send two walkers from the start: a slow one moving 1 node per step and a fast one moving 2.

You see

  • Cycle in a linked list or number sequence
  • Middle of a list
  • Nth node from the end

Learn it in

Linked List TraversalDoubly Linked ListLinked ListDetect Cycle in Graphs

Template

function hasCycle(head) {  let slow = head, fast = head;  while (fast && fast.next) {    slow = slow.next; fast = fast.next.next;    if (slow === fast) return true;  }  return false;}

Practice problems