Single Element in a Sorted Array in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 27-Feb-2020 10:10:59
Advertisements