Skip to content

Commit 921b21d

Browse files
committed
Array: Find first duplicate value in C++ #1081
1 parent 9e50c2f commit 921b21d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Arrays/find_first_duplicate_value.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function
3+
that returns the first integer that appears more than once (when the array is read from left to right).
4+
5+
Sample Input = [2, 1, 5, 2, 3, 3, 4]
6+
Output : 2
7+
8+
Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution
9+
*/
10+
11+
#include <bits/stdc++.h>
12+
using namespace std;
13+
14+
class Solution{
15+
public:
16+
// O(N) time complexity and O(N) Space Complexity Solution
17+
int findDuplicate1(vector<int>& nums)
18+
{
19+
int N=nums.size();
20+
21+
// Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity
22+
vector<bool> trk(N,false);
23+
24+
for(int i=0;i<N;i++)
25+
{
26+
if(trk[nums[i]]==true) return nums[i];
27+
trk[nums[i]]=true;
28+
}
29+
return -1;
30+
}
31+
32+
// O(N) time complexity and O(1) Space Complexity Solution
33+
int findDuplicate2(vector<int>& nums)
34+
{
35+
int N=nums.size();
36+
for(int i=0;i<N;i++)
37+
{
38+
if(nums[abs(nums[i])]<0) return nums[i];
39+
nums[abs(nums[i])]*=-1;
40+
}
41+
return -1;
42+
}
43+
};

0 commit comments

Comments
 (0)