PatternsFast & Slow Pointers

Fast & Slow Pointers Pattern

Tools for linked‑list cycle detection, middle‑node finding, and removing duplicates.

1 Problems
3‑4 Hours
Easy → Medium

When to Use Fast & Slow Pointers

Cycle Detection

Detect cycles in linked structures using Floyd’s algorithm

Finding Middle/Median Node

Fast moves 2×, slow 1× to find midpoint

Removing Duplicates

Slow pointer marks end of cleaned list, fast scans ahead

Linked‑List Processing

Any problem with “gap” or spacing in lists

Key Insights & Tips

Time Complexity

O(n), two pointers traverse at different speeds

Space Efficiency

O(1) extra space — no new structures

Common Mistake

Not advancing fast pointer twice or handling null checks

Pro Tip

Always check `fast && fast.next` in the loop condition

Code Examples

Cycle Detection (Floyd’s Algorithm)

Detect cycle in linked list using fast/slow pointers

Time: O(n)Space: O(1)
function hasCycle(head: ListNode | null): boolean {
  let slow = head, fast = head
  while (fast && fast.next) {
    slow = slow.next!
    fast = fast.next.next!
    if (slow === fast) return true
  }
  return false
}

Find Middle of Linked List

Fast pointer moves 2x, slow moves 1x to find middle

Time: O(n)Space: O(1)
function middleNode(head: ListNode | null): ListNode | null {
  let slow = head, fast = head
  while (fast && fast.next) {
    slow = slow!.next!
    fast = fast.next.next
  }
  return slow
}

Remove Duplicates from Sorted List

Use slow pointer to build unique portion, fast to scan ahead

Time: O(n)Space: O(1)
function deleteDuplicates(head: ListNode | null): ListNode | null {
  let dummy = new ListNode(0), tail = dummy
  let curr = head
  while (curr) {
    if (!tail.next || tail.next.val !== curr.val) {
      tail.next = curr
      tail = tail.next
    }
    curr = curr.next
  }
  tail.next = null
  return dummy.next
}

Your Progress

Problems Solved0/1
0% complete1 remaining

Practice Problems

View All

String Compression

medium

Asked by Companies

GoogleAmazonMicrosoftFacebookAdobeUber

Next Pattern

Onward to the next challenge?

Graph Traversal