Find the Duplicate Number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return *this repeated number*. You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
Examples
Constraints
1 <= n <= 10^5nums.length == n + 11 <= nums[i] <= nAll the integers in nums appear only once except for precisely one integer which appears two or more times.
Floyd's Tortoise and Hare (Cycle Detection)
Approach
1. We can view the array as a linked list where the index represents a node and the value at that index represents the `next` pointer (`next = nums[index]`). 2. Because the array contains `n + 1` integers between `1` and `n`, there must be at least one duplicate, meaning multiple nodes point to the same next node. This guarantees a cycle. 3. We use Floyd's Cycle Detection algorithm. We initialize two pointers, `slow` and `fast`, both starting at the first element `nums[0]`. 4. We move `slow` one step (`nums[slow]`) and `fast` two steps (`nums[nums[fast]]`) until they meet. This proves there is a cycle. 5. To find the start of the cycle (the duplicate number), we move `slow` back to `nums[0]` and keep `fast` at the intersection point. 6. We then move both `slow` and `fast` one step at a time. The point where they meet again is the entrance to the cycle, which is our duplicate number.
Complexity Analysis
This approach satisfies the constraints of not modifying the array and using O(1) space.