
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the element that appears once in an array where every other element appears twice in C++
Suppose we have an array A. In this array there are different numbers that occurs twice. But there is only one number that occurs once. We have to find that element from that array.
Suppose A = [1, 1, 5, 3, 2, 5, 2], then the output will be 3. As there are each number twice, we can perform XOR to cancel out that element. because we know y XOR y = 0
To solve this, we will follow these steps.
Take one variable res = 0
for each element e in array A, preform res := res XOR e
return res
Example
Let us see the following implementation to get better understanding −
class Solution(object): def singleNumber(self, nums): ans = nums[0] for i in range(1,len(nums)): ans ^=nums[i] return ans ob1 = Solution() print(ob1.singleNumber([1,1,5,3,2,5,2]))
Input
[1,1,5,3,2,5,2]
Output
3
- Related Articles
- Find the element that appears once in sorted array - JavaScript
- 8085 program to find the element that appears once
- First element that appears even number of times in an array in C++
- Take an array and find the one element that appears an odd number of times in JavaScript
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Find the only element that appears b times using C++
- Return the element that appears for second most number of times in the array JavaScript
- Get the item that appears the most times in an array JavaScript
- Create a tooltip that appears when the user moves the mouse over an element with CSS
- Count Derangements (Permutation such that no element appears in its original position) in C++
- Return the index of first character that appears twice in a string in JavaScript
- Maximum difference between two elements such that larger element appears after the smaller number in C
- How to find the one integer that appears an odd number of times in a JavaScript array?
- How to find every element that exists in any of two given arrays once using JavaScript?
- Divide every element of one array by other array elements in C++ Program

Advertisements