imashutosh51

Single Number II

Jan 28th, 2026
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. #bit counting at every position and consider those bits whose count%3==1 because if the number occured once then either a bit at any position can be 1 or 4(if all elements have also that bit)
  2. #T.C=32*n n=total number of elements for each element.
  3. class Solution:
  4.     def singleNumber(self, nums: List[int]) -> int:
  5.         result = 0
  6.  
  7.         for bit in range(32):
  8.             count = 0
  9.             for num in nums:
  10.                 if (num >> bit) & 1:
  11.                     count += 1
  12.  
  13.             if count % 3 != 0: #Right shift 'num' by 'bit' positions will make that bit at 1st place from right Then AND with 1 to check if that bit is set (1) or not (0)
  14.                 result |= (1 << bit) # if set then do or in the result at that position.
  15.  
  16.         # handle negative number (32-bit signed)
  17.         if result >= 2**31:
  18.             result -= 2**32
  19.  
  20.         return result
  21.  
  22.  
  23.  
  24. #Time complexity O(n), no space used
  25. class Solution:
  26.     def singleNumber(self, nums: List[int]) -> int:
  27.         ones=0 #it will store only those elements which occurs once but not third time element
  28.         twos=0 #it will store only those elements which occurs twice
  29.         for i in nums:
  30.             ones= (ones^i) & ~twos
  31.             twos=(twos^i) & ~ones
  32.         return ones #finally ones will have a element which will have the frequency of 1
  33.        
Advertisement
Add Comment
Please, Sign In to add comment