A duplicate number within an array of size n+1 can be found efficiently using a few different approaches. The most common method involves leveraging the array’s indices to track element occurrences, often modifying the array in place. This allows for a solution with linear time complexity (O(n)) and constant extra space (O(1)).
Here’s a breakdown of the approach:
- Initialization:
- Assume the array contains numbers from 1 to n, with one number appearing twice.
- Create a variable n to store the size of the array.
- Iteration and Modification:
- Iterate through the array elements using a loop.
- For each element nums[i], calculate its corresponding index abs(nums[i]) - 1.
- Check the sign of nums[abs(nums[i]) - 1].
- If it’s negative, you’ve found the duplicate (it was already marked negative in a previous iteration).
- If it’s positive, change the sign of nums[abs(nums[i]) - 1] to mark it as visited.
- Duplicate Identification:
- If a negative element is encountered, the absolute value of the corresponding index plus one ( abs(nums[i])) represents the duplicate number.
Here’s an example in Python:
def find_duplicate(nums):
for num in nums:
if nums[abs(num) - 1] < 0:
return abs(num)
nums[abs(num) - 1] *= -1
# Example usage:
nums = [1, 2, 3, 4, 2]
duplicate = find_duplicate(nums)
print(f"The duplicate number is: {duplicate}")#include <iostream>
using namespace std;
int findDublicate(int *arr, int n) {
for (int i = 0; i < n; i++) {
if (arr[abs(arr[i]) - 1] < 0) {
return abs(arr[i]);
}
arr[abs(arr[i]) - 1] *= -1;
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
cout << findDublicate(arr, n);
}This approach modifies the original array, so if preserving the original array is necessary, a copy should be made first. [2]