4.Find the Duplicate Number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one duplicate number in nums, return this duplicate number.
Example 1:
Input: nums = [1,3,4,2,2]
Output: 2
Example 2:
Input: nums = [3,1,3,4,2]
Output: 3
Example 3:
Input: nums = [1,1]
Output: 1
Example 4:
Input: nums = [1,1,2]
Output: 1Solution: (Using Hashset)
class Solution
{
public:
int findDuplicate(vector<int> &nums)
{
unordered_set<int> s;
for (int i = 0; i < nums.size(); i++)
{
if (s.find(nums[i]) == s.end())
{
s.insert(nums[i]);
}
else
{
return nums[i];
}
}
return -1;
}
};Time Complexity: O(n) , Space Complexity: O(n)
Solution II : Floyd's Tortoise and Hare (Cycle Detection)
Here is how it works:

Time Complexity: O(n) , Space Complexity: O(1)
Last updated
Was this helpful?