imashutosh51

Unique Number II

Jan 28th, 2026
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. #User function Template for python3
  2. """
  3. Intuition:
  4. XORing all elements cancels out numbers that appear twice and leaves
  5. the XOR of the two unique numbers (a ^ b).
  6. In this XOR result, at least one bit is set, meaning a and b differ there.
  7. We use that bit to divide all numbers into two groups:
  8. one group where the bit is set and one where it is not.
  9. While XORing numbers inside each group, duplicate numbers cancel again.
  10. Finally, each group contains exactly one unique number.
  11. """
  12.  
  13. '''x = 10 (1010) k = 8 (1000) so x & k = 1000 (which is 8, NOT 1) so check as !=0'''
  14.  
  15. class Solution:
  16.     def singleNum(self, arr):
  17.         temp=0
  18.         for i in arr:
  19.             temp=temp^i
  20.         k=1
  21.         ans1,ans2=0,0
  22.         for i in range(32):
  23.             if (temp & k) !=0:
  24.                 for j in arr:
  25.                     if j & k !=0:
  26.                         ans1=ans1^j
  27.                     else:
  28.                         ans2=ans2^j
  29.                 return sorted([ans1,ans2])
  30.             k=k<<1
  31.                    
  32.  
Advertisement
Add Comment
Please, Sign In to add comment