Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the only number in an array that doesn't occur twice [duplicate]

The following is taken from a job interview:

In a given array, which contains integers, each number repeats itself once except for one, which doesn't repeat. Write a function that finds the number that doesn't repeat.

I thought about using an HashSet, but it might complicate everything...

Any ideas of a simple solution?

like image 399
Adam Avatar asked Mar 29 '15 19:03

Adam


People also ask

How do you find non repeating numbers in an array?

Finding the non repeating element in an array can be done in 2 different ways. Method 1: Use two loops, one for the current element and the other to check if the element is already present in the array or not. Method 2: Traverse the array and insert the array elements and their number of occurences in the hash table.

How do you check if a number appears twice in an array?

Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1).


2 Answers

You can define an integer "result" initialized to 0, and then you do some bitwise operations by applying a XOR logic to all elements in your array.

At the end, "result" will be equal to the only element that appears only one time.

result = 0 for i in array:   result ^= i return result 

http://en.wikipedia.org/wiki/Bitwise_operation#XOR

For instance, if your array contains the elements [3, 4, 5, 3, 4], the algorithm will return

3 ^ 4 ^ 5 ^ 3 ^ 4

But the XOR operator ^ is associative and commutative, so the result will be also equal to:

(3 ^ 3) ^ (4 ^ 4) ^ 5

Since i ^ i = 0 for any integer i, and i ^ 0 = i, you have

(3 ^ 3) ^ (4 ^ 4) ^ 5 = 0 ^ 0 ^ 5 = 5

like image 50
dhokas Avatar answered Oct 08 '22 23:10

dhokas


I've seen this question before. It's a trick. Assuming all the repeated numbers appear exactly twice you do this:

int result = 0; for (int a : arr)     result ^= a; 
like image 21
Paul Boddington Avatar answered Oct 08 '22 22:10

Paul Boddington