# Find the only different element in an array using C++

C++Server Side ProgrammingProgramming

In this problem, we are given an arr[] of size n. Our task is to find the only different element in an array.

There are only two different types of elements in the array. All the elements are the same except one.

Let’s take an example to understand the problem,

Input

arr[] = {1, 1, 1, 2, 1, 1, 1, 1}

Output

2

## Solution Approach

A simple approach to solve the problem, we need to traverse the array and find elements which are different from other elements of the array. This approach needs a time complexity of O(N2).

Another approach to solve the problem in O(N) is by using a hash table to store elements and their occurrence frequency. And print the value with a single frequency of occurrence.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findDiffElementArray(int arr[], int n){
if (n == 1)
return -1;
if (n == 2)
return arr;
if (arr == arr && arr != arr)
return arr;
if (arr == arr && arr != arr)
return arr;
if (arr == arr && arr != arr)
return arr;
for (int i = 3; i < n; i++)
if (arr[i] != arr[i - 1])
return arr[i];
return -1;
}
int main(){
int arr[] = { 5, 5, 1, 5, 5, 5, 5};
int n = sizeof(arr) / sizeof(arr);
cout<<"The different element in the array is "<<findDiffElementArray(arr, n);
return 0;
}

## Output

The different element in the array is 1