Skip to content
DSA Patterns
Menu
Language
Fast & Slow PointersLC #1423 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Linked List Cycle II

Problem (restated)

Return the node where the cycle begins, or null.

Intuition

After meet, restart one pointer at head; same pace meets at entrance.

Approaches

Floyd's cycle entry

Unverified
Time O(n)Space O(1)

Idea. Detect cycle with fast/slow; then head and meet walk until equal.

Walkthrough. Cycle starting at node 2: second phase returns that node.

Trade-offs. Hash set of seen nodes is O(n) space.

Solution
Show helper code
export class ListNode {
  val: number; next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export class ListNode {
  val: number; next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export function detectCycle(head: ListNode | null): ListNode | null {
  if (!head?.next) return null;
  let slow: ListNode | null = head, fast: ListNode | null = head;
  while (fast?.next) {
    slow = slow!.next; fast = fast.next.next;
    if (slow === fast) {
      let p: ListNode | null = head;
      while (p !== slow) { p = p!.next; slow = slow!.next; }
      return p;
    }
  }
  return null;
}
export function detectCycle(head: ListNode | null): ListNode | null {
  if (!head?.next) return null;
  let slow: ListNode | null = head, fast: ListNode | null = head;
  while (fast?.next) {
    slow = slow!.next; fast = fast.next.next;
    if (slow === fast) {
      let p: ListNode | null = head;
      while (p !== slow) { p = p!.next; slow = slow!.next; }
      return p;
    }
  }
  return null;
}

Template connection

Phase one is the same meeting as cycle detection. Then one pointer starts at the head and one at the meeting point, one step each. They meet at the cycle entrance. That entrance is the head only when the cycle starts there.

Reflection

  • Finding a cycle is not enough; you need the entry. Why does one pointer reset to the head while both then move +1?
  • No cycle returns null. If the cycle is the whole list, is the entry the head?
  • State the relation between the meeting point and the entry in one sentence.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Cycle starts at 2. Floyd: slow +1, fast +2 until they meet.

3head2entry0-4
Key:CurrentActive rangeLeft / slowRight / fastMatchSettled