Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```
- To understand this solution there are a couple of important bitwise xor properties that you must keep in mind. Skip to the bottom if know these already.
- a ⊕ b = b ⊕ a and a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c
- 1.xor is commutative and associative.
- a ⊕ b = c => a ⊕ c = b => b ⊕ c = a
- 2.xor is the inverse of itself.
- x ⊕ x = 0
- 3.Therefore, we can say that if a number x appeares an even number of times ⊕ operation will cancel it out.
- Formally, x ⊕ x ⊕ x ⊕ x .... n times = 0, where n is even.
- y = x & (x-1)
- 4.This is more of a trick rather than a property to strip the lowest set bit of a number. You would've already known this If you're familliar with BIT, Binary lifting or Binary exponentation.
- Finally, to solve this problem:
- Find the xor of the two numbers a and b that only occur once by xor-ing the entire array. Property 3
- The two numbers a and b must differ by at least one bit, otherwise their xor would've been 0. Lets say b is the number that has the lowest set bit and a has the lowest unset bit.
- Find a by xor-ing all those numbers that have the lowest unset bit. Property 4
- Once you have a we can find b by xor-ing with xor of the entire array. Property 2
- ```
- class Solution:
- def singleNumber(self, nums):
- res=0
- for i in nums:
- res=res^i
- last_setbit=res&(-res)
- ans=[0,0]
- for i in nums:
- if i& last_setbit==0:
- ans[0]=ans[0]^i
- else:
- ans[1]=ans[1]^i
- ans.sort()
- return ans
Add Comment
Please, Sign In to add comment