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


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[0];
   if (arr[0] == arr[1] && arr[0] != arr[2])
      return arr[2];
   if (arr[0] == arr[2] && arr[0] != arr[1])
      return arr[1];
   if (arr[1] == arr[2] && arr[0] != arr[1])
      return arr[0];
   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[0]);
   cout<<"The different element in the array is "<<findDiffElementArray(arr, n);
   return 0;
}

Output

The different element in the array is 1

Updated on: 11-Feb-2022

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements