Find single in an array of 2n+1 integer elements in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array consisting of (2n+ 1) integer values. Out of all these values, n elements appear twice in the array and there is only one element in the array that appears once. Our task is to Find single in an array of 2n+1 integer elements.

Let’s take an example to understand the problem,

Input

arr[] = {1, 3, 5, 6, 5, 1, 3}

Output

5

Solution Approach

A simple solution to the problem is using a counter for the elements. If an element is encountered, store its value and occurrence count. After this search for the element in the table which has occurrence count = 1. A more efficient solution would be using XOR. Here, we will perform XOR of all the elements of the array. This XOR will make all the elements with double occurrence 0. And the only element whose value will be present is the one whose occurrence is 1.

This is because of the properties of XOR that are −

- a^a = 0
- a^0 = a

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findSingleValue(int arr[], int n) {
   int element = 0;
   for (int i = 0; i < n; i++)
      element = element ^ arr[i];
   return element;
}
int main() {
   int arr[] = { 1, 3, 5, 6, 5, 1, 3 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The element of the array with single occurrence is "<<findSingleValue(arr, n);
   return 0;
}

Output

The element of the array with single occurrence is 6
raja
Published on 16-Mar-2021 06:20:24
Advertisements