Find the Unique Number

Solve a problem based on bit-masking to find a unique number.

Problem statement

You are given a list of numbers in which every number is occurring twice except for one number. Find out the unique number.

Solution: Bit-masking approach

For this problem, we can use the logical XOR operation.

For two given logical statements, the XOR function would return TRUE if one of the statements is true and FALSE if both statements are true. If neither of the statements is true, it returns FALSE again.

Let’s look at the following example:

We have two numbers, a = 10 and b = 10. The bit representation will be 1010. When we perform XOR of these two numbers, we get 0.

The same approach we can use to solve this problem. We will perform the XOR operation on all the elements present in the list. At last, the result from XOR will be that unique number.

Let’s look at the implementation now.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.