Solution: Find The Duplicate Number
Let's solve the Find The Duplicate Number problem using the Fast and Slow Pointers pattern.
We'll cover the following
Statement
Given an array of positive numbers, nums
, such that the values lie in the range , inclusive, and that there are numbers in the array, find and return the duplicate number present in nums
. There is only one repeated number in nums
.
Note: You cannot modify the given array
nums
. You have to solve the problem using only constant extra space.
Constraints:
nums.length
-
nums[i]
- All the integers in
nums
are unique except for one integer that will appear more than once.
Solution
We solve this problem using fast and slow pointers technique, without modifying the nums
array and using only constant extra space.
For this problem, the duplicate number will create a cycle in the nums
array. The cycle in the nums
array helps identify the duplicate number.
To find the cycle, we’ll move in the nums
array using the function, where is the index of the array. This function constructs the following sequence to move:
In the sequence above, every new element is an element in nums
present at the index of the previous element.
Let’s say we have an array, . We’ll start with , which is , present at the index of the array and then move to , which is , present at the index. Since we found at the index, we’ll move to the index, and so on. This example shows that if we’re given an array of length , with values in the range , we can use this traversal technique to visit all the locations in the array.
The following example illustrates this traversal:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.