Typorithm · medium

Fast & Slow Pointers

fast-slow-pointerspatternslinked-listcycle-detection
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Fast & Slow Pointers

0%

Basic Patterns

Two pointers at different speeds meet only if the structure loops.

A slow pointer moves one step per turn while a fast pointer moves two.

If the list ends, fast hits null and the answer is no cycle.

If the list loops, fast eventually laps slow and they point at the same node.

01

Same start, different speeds.

02

Guard both fast and fast.next.

03

Identity match means a cycle.

function hasCycle(head) {
  let slow = head;
  let fast = head;

  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;

    if (slow === fast) {
      return true;
    }
  }

  return false;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Two speeds

Both runners start at the head; speed difference does the work.

let slow = head;
  let fast = head;

2. Loop guard

fast moves two steps, so both fast and fast.next must exist.

while (fast && fast.next)

3. Step both

slow advances one node while fast advances two.

slow = slow.next;
    fast = fast.next.next;

4. Meeting check

In a cycle the fast runner laps the slow one and they share a node.

if (slow === fast)

5. No cycle

If fast reaches the end, the list terminates and has no cycle.

return false

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Fast & Slow Pointers: Lesson & Practice · Typorithm | ApplyDjinn