Find the duplicate number
Treat each value as a pointer to an index. Because values are in 1..n and there are n+1 of them, following those pointers must eventually revisit a node — and the entrance to that cycle is the duplicate. Floyd's tortoise and hare finds it in O(n) time and O(1) space.
Overview
Read the constraints first
The easy answers are all excluded on purpose. A set is O(n) space. Sorting modifies the array. Marking visited indices by negating them modifies it too. Each constraint removes one obvious solution, and what is left is the intended one — which is why reading the constraints aloud is a real technique, not a stall.
Step through it
What to watch
- The two pointers move at different speeds until they meet.
- Meeting is not the answer — phase two finds the entrance.
- Nothing is written to the array and nothing is allocated.
Say this out loud
"The constraints rule out sorting and a set. If you read each value as a next-pointer, the array is a linked list that must contain a cycle, and the cycle entrance is the duplicate - so it's Floyd's algorithm."