- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
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
- Related Articles
- Missing Element in Sorted Array in C++
- Check for Majority Element in a sorted array in C++
- Maximum element in a sorted and rotated array in C++
- k-th missing element in sorted array in C++
- C++ program to search an element in a sorted rotated array
- Find missing element in a sorted array of consecutive numbers in C++
- Element Appearing More Than 25% In Sorted Array in C++
- Checking for majority element in a sorted array in JavaScript
- Count of only repeated element in a sorted array of consecutive elements in C++
- Find position of an element in a sorted array of infinite numbers in C++
- Floor in a Sorted Array in C++
- Finding the first unique element in a sorted array in JavaScript
- Finding first unique element in sorted array in JavaScript
- Find the only repeating element in a sorted array of size n using C++
- Find index of an extra element present in one sorted array in C++

Advertisements