
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Single Number in Python
- Single Number III in C++
- Single-Row Keyboard in python
- A single neuron neural network in Python
- Print Single and Multiple variable in Python?
- Multiple Assignments to Single Value in Python
- Ugly Number II in C++
- Confusing Number II in C++
- Strobogrammatic Number II in C++
- 4Sum II in Python
- How to encapsulate Python modules in a single file?
- Spiral Matrix II in Python
- Basic Calculator II in Python
- Course Schedule II in Python
- Reverse String II in Python
