Single Number II in Python



Suppose we have a non-empty array of integers, every element appears three times except for one, which appears exactly once. We have to find a single element. So if the array is [2,2,3,2] then the output will be 3.

To solve this, we will follow these steps −

  • find the maximum number by taking the absolute value of the elements from the array and store it into max_num

  • max_bits := integer of (log max_num base 2) + 2

  • list1 := an empty list of size max_bits and whose elements are 0

  • for each num in nums −

    • pos := 0

    • while num is not 0 and pos < max_bit

      • if no is odd, then increase list1[pos] by 1

      • n := n / 2 and increase pos by 1

  • for i in range 0 to max_bits

    • list1[i] := list1[i] mod 3

  • pos := 0, res := 0

  • for i in range max_bits

    • if list1[i] is not 0, then result := result + 2^pos

    • pos := pos + 1

  • if list1[max_bits - 1] is 1, then res := -(2^max_bits - res)

  • return res

Example (Python)

Let us see the following implementation to get better understanding −

import math
class Solution(object):
   def singleNumber(self, nums):
      max_num = max(map(abs, nums))
      max_bits = (int)(math.log(max_num,2)) + 2
      list1 = [0 for i in range(max_bits)]
      for no in nums:
         pos = 0
         while (no != 0 and pos < max_bits):
            if (no & 1 != 0):
               list1[pos] += 1
            no >>= 1
            pos += 1
      for i in range(max_bits):
         list1[i] %= 3
      pos = 0
      result = 0
      for i in range(max_bits):
         if (list1[i] != 0):
            result += (2 ** pos)
         pos += 1
      print (list1, max_bits)
      if (list1[max_bits - 1] == 1):
         result = -(2 ** max_bits - result)
      return (result)
ob = Solution()
print(ob.singleNumber([2,2,3,2]))

Input

[2,2,3,2]

Output

[1, 1, 0] 3
3

Advertisements