Wednesday, August 13, 2014

Repeating number problem - 3


Given a (potentially large) array of integers, all but one repeating an even number of times, how would you find the one repeating an odd number of times in an efficient way? eg [1 2 3 3 2 2 1 4 2] should return 4

Method 1: Use map data structure to track the occur times of the number in the list. Then loop through the map to find the number occurs even times.
Output:
Number occur even times: 6


Method 2: Find the unique set of the integer array and append the unique set to the original array. Then XOR the new array leaving only the number repeat even times. The trick is XOR with odd times itself remains zeros, XOR with even times itself remains itself.
Output:
Number that occurs even times: 6

No comments:

Post a Comment