Similar Problems

Similar Problems not available

Single Number Iii - Leetcode Solution

Companies:

LeetCode:  Single Number Iii Leetcode Solution

Difficulty: Medium

Topics: bit-manipulation array  

Single Number III Problem on LeetCode is a problem where we are given an array of integers where every element appears twice except for two elements which appear only once. We need to find the two elements which appear only once and return them in any order.

To solve the problem, we need to use the XOR approach. In this approach, we XOR all the elements in the array and get the XOR of the two elements which appear only once. Let's denote this XOR by xorOfTwo. We know that there is at least one set bit in xorOfTwo as the two elements are different and can't have the same bits. We can use one set bit to separate the given array into two groups. One group contains the elements with that set bit, and the other group contains the elements without that set bit.

To do this, we loop over the array and check if each element has the set bit. If it has, we XOR it with one variable, and if it doesn't have, we XOR it with another variable. At the end of the loop, we will have the two elements we are looking for in these two variables.

Here's the detailed solution -

  1. Initialize two variables, lets call them "first" and "second," with a value of 0.
  2. XOR all the elements in the array. Let's call this XOR "xorOfTwo".
  3. Find the rightmost set bit in "xorOfTwo" using the formula "xorOfTwo & ~(xorOfTwo - 1)". Let's call this "rightmostSetBit".
  4. Loop over the array and check for each element if it has the "rightmostSetBit". If it has, XOR it with "first", otherwise XOR it with "second".
  5. At the end of the loop, "first" and "second" will be the two elements which appeared only once in the array.

Here's the implementation of the solution in Python -

def singleNumber(nums): xorOfTwo = 0

# Step 1 - XOR all the elements in the array
for num in nums:
    xorOfTwo ^= num

# Step 2 - Find the rightmost set bit in "xorOfTwo"
rightmostSetBit = xorOfTwo & ~(xorOfTwo - 1)

# Initialize two variables
first = 0
second = 0

# Loop over the array and separate the elements into two groups
for num in nums:
    if num & rightmostSetBit:
        first ^= num
    else:
        second ^= num

# Return the two elements which appeared only once in the array
return [first, second]

Test the function with the given test cases

print(singleNumber([1,2,1,3,2,5])) # Output - [3,5]

Single Number Iii Solution Code

1