forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneOddOccurring_Efficient_Solution.cpp
More file actions
62 lines (49 loc) · 1.57 KB
/
OneOddOccurring_Efficient_Solution.cpp
File metadata and controls
62 lines (49 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//Problem - One Odd Occurring
//Given an array of integers where all elements appear even number of times except only one element which appears odd no. of times
//Find that one odd-occurring element
/*
There are many ways to solve this -
(1) Simple Method -
Traverse array linearly and for every element, check how many times it occur in array by traversing array linearly again for that element
And if an element comes odd number of times , the return that
So Time-Complexity = O(n^2)
(2) Better Solution -
Use Hashing to count no. of occurances of every element
So , Time-Complexity = O(n)
And , Auxiliary-Space = O(n)
(3) Efficient Solution -
Using XOR Operator -
Use following property of XOR -
-> x^0 = x
-> x^y = y^x
-> x^x = 0
So ,
We do xor of all elements of array so that-
-> All even ocuuring elements cancel out each-other i.e., become 0
-> So Finally, We have the element which is odd occuring
So Here -
Time-Complexity = O(n)
Auxiliary Space = O(1)
*/
//So Solution 3 -
//Using XOR Operator ->
#include <iostream>
using namespace std;
int findOddOccuringElement (int givenArray[] , int numberOfElements)
{
int result = 0; //Because :- x^0 = x
for(int iteratorIndex=0 ; iteratorIndex<numberOfElements ; iteratorIndex++)
result = result ^ givenArray[iteratorIndex];
return result;
}
int main()
{
int sizeOfArray;
cin>>sizeOfArray;
int array[1000];
for(int index=0 ; index<sizeOfArray ; index++)
cin>>array[index];
int answer = findOddOccuringElement (array,sizeOfArray);
cout<<"One odd-occurring element in array is = "<<answer<<endl;
return 0;
}