Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a number that repeats even no of times where all the other numbers repeat odd no of times

Tags:

algorithm

Given is an array of integers. Each number in the array repeats an ODD number of times, but only 1 number is repeated for an EVEN number of times. Find that number.

I was thinking a hash map, with each element's count. It requires O(n) space. Is there a better way?

like image 813
shreyasva Avatar asked Sep 03 '11 11:09

shreyasva


4 Answers

Hash-map is fine, but all you need to store is each element's count modulo 2. All of those will end up being 1 (odd) except for the 0 (even) -count element.

(As Aleks G says you don't need to use arithmetic (count++ %2), only xor (count ^= 0x1); although any compiler will optimize that anyway.)

like image 155
smci Avatar answered Sep 21 '22 23:09

smci


I don't know what the intended meaning of "repeat" is, but if there is an even number of occurrences of (all-1) numbers, and an odd number of occurances for only one number, then XOR should do the trick.

like image 25
wildplasser Avatar answered Sep 19 '22 23:09

wildplasser


You don't need to keep the number of times each element is found - just whether it's even or odd number of time - so you should be ok with 1 bit for each element. Start with 0 for each element, then flip the corresponding bit when you encounter the element. Next time you encounter it, flip the bit again. At the end, just check which bit is 1.

like image 39
Aleks G Avatar answered Sep 22 '22 23:09

Aleks G


If all numbers are repeated even times and one number repeats odd times, if you XOR all of the numbers, the odd count repeated number can be found.

By your current statement I think hashmap is good idea, but I'll think about it to find a better way. (I say this for positive integers.)

like image 45
Saeed Amiri Avatar answered Sep 18 '22 23:09

Saeed Amiri