Fast & Slow Pointers

Linear Helpers

Signal

Linked list cycle/middle/nth-from-end

Template

Two pointers at different speeds (tortoise and hare).

Worked example (1)

#5

Fast & Slow Pointers

Fast & Slow Pointers (Floyd's)

An array of n + 1 integers has each value in the range 1..n; exactly one value repeats. Find it using O(1) extra space without modifying the array.

function findDuplicate(nums: number[]): number {
  let slow = nums[0], fast = nums[0];
  do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow !== fast);
  slow = nums[0];
  while (slow !== fast) { slow = nums[slow]; fast = nums[fast]; }
  return slow;
}
Insight

The O(1)-space / no-modify constraints are what force this over a hashmap.