To find a non-repetitive element in an array the first thing that comes to mind is that if we first sort the array and then try to manipulate it. The sorting process is easy and as follows:
int arr[] = {/*Some array*/};
int arrSize = sizeof(arr)/sizeof(int);
//Lets sort the array
for(int i=0;i<arrSize;i++)
{
for(int j=i;j<arrSize;j++)
{
if(arr[i]>arr[j])
{
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
After sorting the array we may see different scenarios like:
int arr1[] = {1,1,2,2,3};
int arr2[] = {1,2,2,3,3};
int arr3[] = {1,1,2,3,3};
We have to design an algorithm such that it can differentiate and easily manipulate the three scenarios. Let n be our number. The first scenario is to check if the last isn't the same as the previous one by:
if(arr[arrSize-1] != arr[arrSize-2]) //The last is not the same as the previous
{
n=arr[arrSize-1];
}
The second one is similar to the first:
if(arr[0] != arr[1]) // The first element is not the same as the second
{
n = arr[0];
}
The third one is easy too, we just have to check if two neighbors are never equal to the middle number, this is as follows:
for(int i=1;i<arrSize-1;i++)
{
if(arr[i-1] != arr[i] && arr[i] != arr[i+1])
{
n=arr[i];
break;
}
}
And so the full code would become:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,2,3,1};
int arrSize = sizeof(arr)/sizeof(int);
//Lets sort the array
for(int i=0;i<arrSize;i++)
{
for(int j=i;j<arrSize;j++)
{
if(arr[i]>arr[j])
{
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
int n;
if(arr[0] != arr[1]) // The first element is not the same as the second
{
n = arr[0];
}
else if(arr[arrSize-1] != arr[arrSize-2]) //The last is not the same as the previous
{
n=arr[arrSize-1];
}
else //Lets search for a number such that its not the same as the numbers on the left and on the right
{
for(int i=1;i<arrSize-1;i++)
{
if(arr[i-1] != arr[i] && arr[i] != arr[i+1])
{
n=arr[i];
break;
}
}
}
cout << n;
}
The Second Way (Better one).
Here's another way we could solve this problem. Suppose that I have a number n=3, if i XORed it with 3 i will get 0, so if we have an array lets say arr[] = {1,2,1}, I first assign n=0, then XOR it with the firs element (1), next I XOR n with the second element and then with the third element. What will happen? The third XOR will cancel the effect of the first thus n will equal to 1. Sample Code:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,2,3,1};
int arrSize = sizeof(arr)/sizeof(int);
int n=0;
for(int i=0;i<arrSize;i++)
{
n^=arr[i];
}
cout << n;
}
This code is O(n).