n + 1 numbers in 1..n, one repeated. Treat each value as a pointer to an index: the duplicate starts a cycle, and fast and slow runners find it.
▼The problem
LeetCode 287 (Medium). An array nums holds n + 1 integers, each in [1, n], and exactly one value repeats (possibly many times). Return that value without modifying the array, using only O(1) extra space.
The examples are LeetCode's: [1,3,4,2,2] → 2, [3,1,3,4,2] → 3 and [3,3,3,3,3] → 3. The video uses the first two in scene 2 and flashes the third in scene 1. The walkthrough (scenes 4–6), the code scene and the outro all run [1,3,4,2,2].
Scene 3 shows the easy ways and the rule each breaks: - a hash set of the values seen (O(n) extra space); - sorting (puts the twins side by side, but changes the array); - checking every pair (n(n+1)/2 = 10 pairs for these five numbers, O(n²) time).
TRY IT ON LEETCODE ▶The solution
def find_duplicate(nums):
slow = fast = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowTranscript
Find the Duplicate Number. You get n plus one numbers, each from one to n, and exactly one value repeats, maybe many times. Return it without changing the array, using only constant extra space.
Take one, three, four, two, two: two appears twice, so return two. And three, one, three, four, two returns three.
The easy ways break a rule. A hash set of everything seen finds it, but costs n extra space. Sorting puts the twins side by side, but changes the array. Checking every pair is n squared: too slow.
Here's the trick. Each slot is a teleporter pad, and its number is the pad it sends you to. Start on pad zero. No number is zero, so nothing ever sends you back there. But two pads send you to the same pad, so the path falls into a loop, and the loop's entrance is the duplicate. It's Linked List Cycle, hiding in an array.
First, catch the loop. Slow jumps once per step, fast jumps twice. Slow to one, fast to three. Slow to three, fast to four. Slow to two, fast to four again. Slow to four: they meet, inside the loop.
Now find the door. Slow restarts at pad zero, and both jump once per step. Slow to one, fast to two. Slow to three, fast to four. Slow to two, fast to two: they meet at the entrance, so the duplicate is two. It works because the entrance is equally far from pad zero and from the meeting pad, give or take whole laps.
In code, both start at pad zero. Slow takes one jump and fast takes two, until they land together. Then slow goes back to zero, and both take single jumps until they meet. Return that pad.
Each phase is at most about n jumps, so the time is linear. Two pointers, and an untouched array: constant space.
Follow the pads, catch the loop, find the door. That's Find the Duplicate Number.