- Related Questions & Answers
- Find the element that appears once in sorted array - JavaScript
- 8085 program to find the element that appears once
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Take an array and find the one element that appears an odd number of times in JavaScript
- 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
- Return the index of first character that appears twice in a string in JavaScript
- Count Derangements (Permutation such that no element appears in its original position) in C++
- Create a tooltip that appears when the user moves the mouse over an element with CSS
- 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?
- Divide every element of one array by other array elements in C++ Program
- Find closest value for every element in array in C++
- Find maximum sum taking every Kth element in the array in C++
- Find the element having different frequency than other array elements in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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]))

[1,1,5,3,2,5,2]

3

Advertisements