Skip to content

visual walkthrough

Find the Duplicate Number

MediumFast & Slow PointersReported at: AmazonMicrosoftMeta+3

Treating an array as a linked list to find a cycle; a famous insight.

Solve on LeetCode

The idea

Each value is between 1 and n, so it's also a valid index. Read nums[i] as "the next node after i" and the array becomes a linked list.

The duplicate value is pointed to from two different indexes, so it's where a cycle begins. Linked List Cycle II's two-phase trick finds it with no extra memory.

Complexity

approachtimespace
Remember what you've seenO(n)O(n)
Cycle detection on indexesO(n)O(1)

More walkthroughs