Single Number III – Leetcode Solution

In this post, we are going to solve the 260. Single Number III problem of Leetcode. This problem 260. Single Number III is a Leetcode medium level problem. Let’s see code, 260. Single Number III – Leetcode Solution.

Problem

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Example 1 :


Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation:  [5, 3] is also a valid answer.

Example 2 :


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

Example 3 :


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

Constraints

  • 2 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each integer in nums will appear twice, only two integers will appear once.

Now, let’s see the code of 260. Single Number III – Leetcode Solution.

Single Number III – Leetcode Solution

260. Single Number III – Solution in Java

class Solution {
    public int[] singleNumber(int[] nums) {
        int xorOfUnique = 0;
        for(int val : nums){
            xorOfUnique ^= val;
        }
        
        int rightSetBitMask = xorOfUnique & -xorOfUnique;
        
        int x = 0, y=0;
        
        for(int val : nums){
            if((val & rightSetBitMask) == 0){
                x ^= val;
            }else{
                y ^= val;
            }
        }
        
        int[] ans = new int[2];
        ans[0] = x;
        ans[1] = y;
        
        return ans;
    }
}

260. Single Number III – Solution in C++

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int xorOfUnique = 0;
        for(int val : nums){
            xorOfUnique ^= val;
        }
        
        int rightSetBitMask = xorOfUnique & -xorOfUnique;
        
        int x = 0, y=0;
        
        for(int val : nums){
            if((val & rightSetBitMask) == 0){
                x ^= val;
            }else{
                y ^= val;
            }
        }
        
        vector<int> ans(2);
        ans[0] = x;
        ans[1] = y;
        
        return ans;
    }
};

260. Single Number III – Solution in Python

class Solution(object):
    def singleNumber(self, nums):
        ans=0
        for item in nums:
            ans=ans^item
        t=ans
        count=0
        while(t):
            if t&1==1:
                break
            count+=1
            t=t>>1
        b=ans
        for item in nums:
            if (item>>count)&1==1:
                b=b^item
        return [b,ans^b]

Note: This problem 260. Single Number III is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *