- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
Advertisements