...

/

Solution: Find the Duplicate Number

Solution: Find the Duplicate Number

Let's solve the Find the Duplicate Number problem using the Fast and Slow Pointers pattern.

Statement

Given an array of positive numbers, nums, such that the values lie in the range [1,n][1, n], inclusive, and that there are n+1n+1 numbers in the array, find and return the duplicate number present in nums. There is only one repeated number in nums, but it may appear more than once in the array.

Note: You cannot modify the given array nums. You have to solve the problem using only constant extra space.

Constraints:

  • 1n1031 \leq n \leq 10^3
  • nums.length =n+1= n + 1
  • 11 \leq nums[i] n\leq n
  • All the integers in nums are unique except for one integer that will appear more than once.

Solution

This solution involves two key steps: identifying the cycle and locating the entry point of this identified cycle, which represents the duplicate number in the array.

The fast and slow pointers technique detects such cycles efficiently, where one pointer takes one step at a time and the other advances by two steps. Initially pointing at the start of the array, the position of each pointer for the next step is determined by the current value they are pointing to. If a pointer points to the value 55 at index 00, its next position will be index 55. As the pointers traverse the array, both will eventually catch up because there’s a cycle. This is because, in the noncyclic part, the distance between the pointers increases by one index in each iteration. However, once both pointers enter the cyclic part, the fast pointer starts closing the gap on the slow pointer, decreasing the distance by one index each iteration until they meet.

Once the duplicate number is confirmed, we reset one of the pointers (usually the slow pointer) to index 00 while the other stays at the position where the pointers met. Then, both pointers move one step at a time until they meet again. With this positioning and pace of pointers, pointers are guaranteed to meet at the cycle’s starting point, corresponding to the duplicate number.

Now, let’s look at the detailed workflow of the solution:

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 f(x)=nums[x]f(x) = nums[x], where xx is the index of the array. This function constructs the following sequence to move:

                      x, nums[x], nums[nums[x]], nums[nums[nums[x]]], ...\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space x, \space nums[x], \space nums[nums[x]], \space nums[nums[nums[x]]], \space ... ...

OSZAR »