
Sponsored
Sponsored
This approach uses cycle detection to find the duplicate number using two pointers. Imagine the numbers in the array form a linked list, where the value at each index points to the next index. When there is a duplicate, a cycle will be formed. The first step is to find the intersection point of the cycle using a slow and fast pointer. Once they meet, use two pointers to find the entrance of the cycle, which will be the duplicate number. This method doesn't modify the array and uses O(1) space.
Time Complexity: O(n), where n is the size of the array. Space Complexity: O(1), since we use a constant amount of extra space.
1
2public class Solution {
3 public int FindDuplicate(int[] nums) {
4 int slow = nums[0];
5 int fast = nums[0];
6 do {
7 slow = nums[slow];
8 fast = nums[nums[fast]];
9 } while (slow != fast);
10 slow = nums[0];
11 while (slow != fast) {
12 slow = nums[slow];
13 fast = nums[fast];
14 }
15 return slow;
16 }
17}
18This C# solution applies Floyd's cycle detection technique to find and return the duplicate number, employing two pointers that traverse the array as if it were a linked list.
This approach leverages a binary search technique on the range of possible values of the duplicate number. For each midpoint in this range, count how many numbers are less than or equal to it. If the count is greater than the midpoint, the duplicate must be in the lower range; otherwise, it is in the upper range. Binary search is applied until the duplicate is found. This doesn't require additional space and doesn't alter the input array.
Time Complexity: O(n log n). Space Complexity: O(1).
1This C solution uses binary search on the range of possible numbers, counting numbers less than or equal to the midpoint, and then adjusting the binary search boundaries accordingly, eventually discovering the duplicate number.