Single Number II LeetCode Solution

Problem – Single Number II LeetCode Solution

Given an integer array nums where every element appears three times except for one, which appears exactly onceFind the single element and return it.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,3,2]
Output: 3

Example 2:

Input: nums = [0,1,0,1,0,1,99]
Output: 99

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each element in nums appears exactly three times except for one element which appears once.

Single Number II LeetCode Solution in Python

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)   

Single Number II LeetCode Solution in C++

   int singleNumber(vector<int>& s) 
    {
    	vector<int> t(32);////Made a array contain 32 elements.
    	int sz = s.size();
    	int i, j, n;
    	for (i = 0; i < sz; ++i)
    	{
    		n = s[i];
    		for (j = 31; j >= 0; --j)
    		{
    			t[j] += n & 1;//Find the last digit.
    			n >>= 1;
    			if (!n)
    				break;
    	    }
        }
	int res = 0;
	for (j = 31; j >= 0; --j)
	{
		n = t[j] % 3;//"3" represents k times. 
		if (n)
			res += 1 << (31 - j);
	}
	return res;
}

Single Number II LeetCode Solution in Java

public int singleNumber(int[] nums) {
  int ones = 0, twos = 0, threes = 0;
        
  for (int i = 0; i < nums.length; i++) {
    // twos holds the num that appears twice
    twos |= ones & nums[i];
    
    // ones holds the num that appears once
    ones ^= nums[i];
 
    // threes holds the num that appears three times
    threes = ones & twos;
            
    // if num[i] appears three times
    // doing this will clear ones and twos
    ones &= ~threes;
    twos &= ~threes;
  }
        
  return ones;
}
Single Number II LeetCode Solution Review:

In our experience, we suggest you solve this Single Number II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Single Number II LeetCode Solution

Find on Leetcode

Conclusion:

I hope this Single Number II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.