# Single Number in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array A. In this array there are many numbers that occur twice. Only one element can be found a single time. 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 is 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 a better understanding −

Live Demo

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
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

nums = [1,1,5,3,2,5,2]

## Output

3
Updated on 28-Apr-2020 09:36:56