Determine if an array of integers from 1 to n contains a duplicate in constant time and space.
MediumYou're given an array nums of n + 1 integers, where every value is between 1 and n inclusive. Exactly one value appears more than once, possibly many times. Return that value.
Solve it without changing nums and using only O(1) extra space.
Example 1
Input: nums = [1, 3, 4, 2, 2] Output: 2
The array holds five values from 1 to 4, and 2 is the one that repeats.
Example 2
Input: nums = [3, 3, 3, 3, 3] Output: 3
The repeated value can fill most of the array.
Constraints
1 <= n <= 10^5nums.length == n + 11 <= nums[i] <= n- Exactly one value appears two or more times.
Approach
Checking every pair takes O(n^2) time, and a hash set of seen values takes O(n) space. Neither meets the limits.
The trick is to read each value as a pointer. From index i, jump to index nums[i]. Every value is between 1 and n, so every jump lands inside the array and the path from index 0 can never stop. With only n + 1 indexes, it must eventually loop. The duplicate value is the index two different positions jump to, which is exactly where the loop begins.
Floyd's algorithm finds that entry point in two phases. First, move slow one jump and fast two jumps at a time until they meet inside the cycle. Then restart slow from the beginning and move both one jump at a time. They meet at the start of the cycle.
Steps
- Set
slowandfasttonums[0]. - Move
slowtonums[slow]andfasttonums[nums[fast]]until they're equal. - Reset
slowtonums[0]. - Move both one jump at a time until they're equal again, then return that value.
Complexity
- Time:
O(n). Each phase takes at most a few passes around the path. - Space:
O(1). Only two pointers, and the array isn't modified.
Common mistakes
- Returning the meeting point of the first phase. That's somewhere inside the cycle, not necessarily its entrance.
- Starting the second phase from index
0while the first phase started fromnums[0]. Both pointers must start the same way in both phases. - Marking values as seen by negating
nums[i]. It works, but it changes the input, which the problem doesn't allow.
Related questions
Given an unsorted integer array that may contain duplicates and a target, find a pair of elements that sums to the target in O(N) time.Given an array of integers, find the first duplicate.Write a function that takes an array of integers and checks for duplicate values in any contiguous window of size N.Related courses




