Iam_Sandeep

Given an integer array nums, in which exactly two elements appear only once and all the other elemen

Jun 13th, 2022 (edited)
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. ```
  2. 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.
  3.  
  4. a ⊕ b = b ⊕ a and a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c
  5. 1.xor is commutative and associative.
  6.  
  7. a ⊕ b = c => a ⊕ c = b => b ⊕ c = a
  8. 2.xor is the inverse of itself.
  9.  
  10. x ⊕ x = 0
  11. 3.Therefore, we can say that if a number x appeares an even number of times ⊕ operation will cancel it out.
  12. Formally, x ⊕ x ⊕ x ⊕ x .... n times = 0, where n is even.
  13.  
  14. y = x & (x-1)
  15. 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.
  16.  
  17. Finally, to solve this problem:
  18.  
  19. Find the xor of the two numbers a and b that only occur once by xor-ing the entire array. Property 3
  20. 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.
  21.  
  22. Find a by xor-ing all those numbers that have the lowest unset bit. Property 4
  23.  
  24. Once you have a we can find b by xor-ing with xor of the entire array. Property 2
  25. ```
  26.  
  27. class Solution:
  28.     def singleNumber(self, nums):
  29.         res=0
  30.         for i in nums:
  31.             res=res^i
  32.        last_setbit=res&(-res)
  33.        ans=[0,0]
  34.        for i in nums:
  35.            if i& last_setbit==0:
  36.                ans[0]=ans[0]^i
  37.            else:
  38.                ans[1]=ans[1]^i
  39.        ans.sort()
  40.        return ans
Add Comment
Please, Sign In to add comment