← Two PointersDSA 1.1.D

Fast/Slow

One pointer at 1 step, one at 2 — cycles and midpoints. Linked List Cycle, Linked List Middle, Remove Nth Node.

StatusCollected
Notes3 solved

The linked-list version of two pointers — no indexing exists on a list, only .next, so "fast" and "slow" have to be actual separate walks instead of arithmetic.

int hasCycle(struct ListNode *head) {
      struct ListNode *slow = head, *fast = head;
      while (fast != NULL && fast->next != NULL) {
          slow = slow->next;
          fast = fast->next->next;
          if (slow == fast) return 1;   /* they met — there's a cycle */
      }
      return 0;   /* fast hit NULL — list terminates cleanly */
  }

If the list actually ends, fast (moving twice as fast) reaches NULL first, no cycle. If it doesn't end, fast eventually laps slow on the loop and they land on the same node — which is impossible on a genuinely terminating list, so that collision is the whole proof. Finding the middle is the same walk, just returning slow once fast runs out instead of checking for a meeting point. Remove Nth Node adds a dummy head node so removing the actual head doesn't need special-casing.

Notes from readers

Comments — via GitHub