- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 Number in Python
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
Let us see the following implementation to get a better understanding −
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ans = nums for i in range(1,len(nums)): ans ^=nums[i] return ans ob1 = Solution() print(ob1.singleNumber([1,1,5,3,2,5,2]))
nums = [1,1,5,3,2,5,2]
- Single Number II in Python
- Single Number III in C++
- Single-Row Keyboard in python
- A single neuron neural network in Python
- Print Single and Multiple variable in Python?
- Multiple Assignments to Single Value in Python
- Subtracting a number from a single MySQL column value?
- How to encapsulate Python modules in a single file?
- Palindrome Number in Python
- Missing Number in Python
- Happy Number in Python
- Largest Number in Python
- Armstrong Number in Python
- Valid Number in Python
- How to Transpose a matrix in Single line in Python?