[
bin manipulation
hash table
]
Leetcode 0137. Single Number II
https://leetcode.com/problems/single-number-ii
There are several 'magical' solutions for this problem I saw in comments, done in O(n), which I really enjoed to read, however I doubt if you never saw this problem you can suceed in real interview. That is why I suggest maybe not the fastest, but much more easier to come up solution. The idea is similar to problem Single Number, but here we need to count each bit modulo 3. So, we
- Iterate over all possible
32bits and for eachnumcheck if thisnumhas non-zero bit on positioniwithnum & (1<<i) == (1<<i)formula. - We evaluate this sum modulo
3. Note, that in the end for each bit we can have either0or1and never2. - Next, update our answer
singlewith evaluated bit. - Finally, we need to deal with overflow cases in python: maximum value for
int32is2^31 - 1, so if we get number more than this value we have negative answer in fact.
Complexity: time complexity is O(32n), which may be not fully honest linear, but is fine for the purpose of this problem. If we want just O(n) complexity, I think problem becomes not medium but hard. Space complexity here is O(1).
class Solution:
def singleNumber(self, nums):
single = 0
for i in range(32):
count = 0
for num in nums:
if num & (1<<i) == (1<<i): count += 1
single |= (count%3) << i
return single if single < (1<<31) else single - (1<<32)
If you like the solution, you can upvote it on leetcode discussion section: Problem 0137