Single Element in a Sorted Array in C++


Suppose we have a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. we have to find this single element that appears only once. So if the array is like [1, 1, 2, 3, 3, 4, 4, 8, 8], then the output will be 2

To solve this, we will follow these steps −

  • ans := 0
  • for i in range 0 to nums array size
    • ans := ans XOR nums[i]
    • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int singleNonDuplicate(vector<int>& nums) {
      int ans = 0;
      for(int i = 0;i < nums.size(); i++)ans ^= nums[i];
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,2,3,3,4,4,8,8};
   cout << (ob.singleNonDuplicate(v));
}

Input

[1,1,2,3,3,4,4,8,8]

Output

2

Updated on: 29-Apr-2020

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements