I have given an array and I need to find is there any duplicate element present in array or not? (I have to take input from the user.)
This is my first code which is giving the wrong answer for some test cases:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unordered_map<int,int> mp;
int temp=1;
for(int i=0,i<n;i++)
{
int x; cin>>x;
if(mp.find(x)!=mp.end())
{
temp=-1; break;
}
mp[x]++;
}
if(temp==-1) cout<<"YES"<<endl; //if duplicate present
else cout<<"NO"<<endl;
mp.clear();
}
return 0;
}
And this code is running perfectly on all the test cases:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unordered_map<int,int> mp;
int temp=1;
for(int i=0,i<n;i++)
{
int x;
cin>>x;
mp[x]++;
}
if(mp.size()<n) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
mp.clear();
}
return 0;
}
what is the reason behind it?