Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #User function Template for python3
- """
- Intuition:
- XORing all elements cancels out numbers that appear twice and leaves
- the XOR of the two unique numbers (a ^ b).
- In this XOR result, at least one bit is set, meaning a and b differ there.
- We use that bit to divide all numbers into two groups:
- one group where the bit is set and one where it is not.
- While XORing numbers inside each group, duplicate numbers cancel again.
- Finally, each group contains exactly one unique number.
- """
- '''x = 10 (1010) k = 8 (1000) so x & k = 1000 (which is 8, NOT 1) so check as !=0'''
- class Solution:
- def singleNum(self, arr):
- temp=0
- for i in arr:
- temp=temp^i
- k=1
- ans1,ans2=0,0
- for i in range(32):
- if (temp & k) !=0:
- for j in arr:
- if j & k !=0:
- ans1=ans1^j
- else:
- ans2=ans2^j
- return sorted([ans1,ans2])
- k=k<<1
Advertisement
Add Comment
Please, Sign In to add comment