You're given an array nums containing n + 1 integers, where each integer is in the range [1, n] inclusive. Here's the catch: exactly one number appears twice, while all others appear exactly once.
Your mission: Find that duplicate number!
The Challenge: You must solve this without modifying the original array and using only constant extra space (O(1)).
Example: If nums = [1,3,4,2,2], then n = 4 and we have 5 integers. The duplicate is 2.
This problem has several elegant solutions - from brute force to a brilliant cycle detection approach that treats the array like a linked list!
Input & Output
Visualization
Time & Space Complexity
Each pointer traverses the array at most twice, giving us linear time
Only using two pointer variables, constant extra space
Constraints
- 1 ≤ n ≤ 105
- nums.length == n + 1
- 1 ≤ nums[i] ≤ n
- All integers in nums appear only once except for exactly one integer which appears twice