Hi,guys here is the simple solution(brute force approach). Time complexity:o(n^2) Space Complexity:o(1)
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,j,n;
cout << "Enter the size of array:\n";
cin >> n;
int arr[n];
//note that there is only one element which occure odd number of times
cout << "Enter the elements of array:\n";
for(i=0;i<n;i++){
cin >> arr[i];
}
//brute force approach
for(i=0;i<n;i++){
int count=0;
for(j=0;j<n;j++){
if(arr[i]==arr[j]){
count++;
}
}
if(count%2==1){
cout << arr[i] ;
break;
}
}
}
Hi,firends we can also solve the above problem using Hash technique:
Time Complexity:o(n)
Space Complexity:o(n)
Here is the code:
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,j,n;
cout << "Enter the size of array:\n";
cin >> n;
int arr[n];
//note that there is only one element which occure odd number of times
cout << "Enter the elements of array:\n";
for(i=0;i<n;i++){
cin >> arr[i];
}
//using hash technique
map<int,int> hash;
for(i=0;i<n;i++){
hash[arr[i]]++;
}
map<int,int>::iterator it;
for(it=hash.begin();it!=hash.end();it++){
if((it->second)%2==1){
cout << it->first << endl;
break;
}
}
}
Hi,guys but this above method is not optimise .
Concept:
The approach for this method is using XOR operation.
.XOR truth table:
1 XOR 1=0
0 XOR 0=0
1 XOR 0=1
0 XOR 1=1
.from xor truth table we can say that xor of a number the same number give 0 as result.
example:
4 XOR 4=0
Conclusion ::
if we take xor of a number with itself even number of times it gives 0.
but if we take xor of a number with itself odd number of times it gives number itself.
Here is the below code.still u have any doubt plz comment below.
Time Complexity:o(n)
Space Complexity:o(1)
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,j,n;
cout << "Enter the size of array:\n";
cin >> n;
int arr[n];
//note that there is only one element which occure odd number of times
cout << "Enter the elements of array:\n";
for(i=0;i<n;i++){
cin >> arr[i];
}
//using XOR operation
int ans;
ans=arr[0];
for(i=1;i<n;i++){
ans=ans^arr[i];
}
cout << ans << endl;
}
No comments:
Post a Comment