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?
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.
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).
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With