Find the Duplicate Number
You'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.
from typing import List
def find_duplicate(nums: List[int]) -> int:
# Treat each value as a pointer to the next index: i -> nums[i].
# The repeated value is where the resulting cycle starts.
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowComplexity
- 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.
simply check its size if the size if the size is greater than n then yes it has duplicate