287. Find the Duplicate Number

Dare2Solve

Dare2Solve

287. Find the Duplicate Number
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Description

The problem is to find the duplicate number in a list of integers. The list is given as an array where each integer appears exactly once, except for one integer that appears twice. The task is to identify this duplicate number.

Intuition

The simplest approach to finding the duplicate is to sort the array and then check adjacent elements for equality. Since the array is sorted, any duplicate numbers will appear consecutively, making it easy to spot the duplicate.

Approach

  1. Sort the Array: First, the array is sorted in ascending order. Sorting will bring the duplicate numbers next to each other.
  2. Find the Duplicate: After sorting, iterate through the array and compare each element with the next one. If two consecutive elements are the same, that number is the duplicate.
  3. Return the Duplicate: Once the duplicate is found, return it. If no duplicates are found (though this case should not happen as per the problem constraints), return -1 or handle the error as appropriate.

Complexity

Time Complexity:

The time complexity is dominated by the sorting step, which is (O(n \log n)), where (n) is the number of elements in the array. The subsequent iteration through the array is (O(n)).

Space Complexity:

The space complexity is (O(1)) if we ignore the space used by the sorting algorithm (since it might use additional space depending on the implementation). Otherwise, it could be (O(n)) if the sort uses additional space.

Code

C++

class Solution {
public:
    int findDuplicate(std::vector<int>& nums) {
        std::sort(nums.begin(), nums.end());
        
        for (size_t i = 0; i < nums.size() - 1; ++i) {
            if (nums[i] == nums[i + 1]) {
                return nums[i];
            }
        }
        
        return -1; // Return -1 or handle error if no duplicate is found
    }
};

Python

class Solution:
    def findDuplicate(self, nums):
        nums.sort()
        
        for i in range(len(nums) - 1):
            if nums[i] == nums[i + 1]:
                return nums[i]
        
        return -1  # Return -1 or handle error if no duplicate is found

Java

public class Solution {
    public int findDuplicate(int[] nums) {
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return nums[i];
            }
        }
        
        return -1; // Return -1 or handle error if no duplicate is found
    }
}

JavaScript

var findDuplicate = function(nums) {

    nums.sort();
    
    for(var i=0;i<nums.length;i++)
    {
        if(nums[i]==nums[i+1])
        return nums[i];
    }
};