Solution: Single Number II
Let's solve the Single Number II problem using the Bitwise Manipulation pattern.
We'll cover the following
Statement
Given a non-empty array arr
, in which exactly two elements appear once, and all the other elements appear twice, return the two elements that appeared only once.
Note: The result can be returned in any order. The solution should use only constant extra space.
Constraints:
arr.length
arr[i]
Solution
The XOR operation is a bitwise operation that returns
We can use any set bit of the result as a way to differentiate between the two unique numbers. In our algorithm, we will use the rightmost set bit. By checking if each element has this set bit or not in the corresponding position, we can consider the array into two groups. One group contains elements with the corresponding set bit, and the other contains elements without it. This allows us to separate the two unique numbers from each other.
Let's look into the algorithm and see how it works.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.