mediumArrayTwo PointersTwo Pointers

Find the Duplicate Number

mediumTime: O(n)Space: O(1)

Signals to notice

find duplicate in array of n+1 values in 1.ncan't modify arrayO(1) space

Brute force first

Sort and scan, or hash set but that costs extra memory. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Floyd's cycle detection: treat the array as a linked list where index i points to nums[i]. The duplicate creates a cycle. Use slow/fast pointers to find the cycle entry point. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

Since there are n+1 values in range [1,n], the pigeonhole principle guarantees a duplicate. The duplicate value creates a cycle in the index-following graph — Floyd's algorithm finds the cycle entry. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Not seeing the linked list analogy — arr[i] is the 'next' pointer. Starting from index 0, following these pointers eventually enters a cycle, and the cycle entry point is the duplicate. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Two Pointers Pattern