6

I am trying to solve this problem: In an integer array all numbers occur exactly twice, except for a single number which occurs exactly once.

A simple solution is to sort the array and then test for non repetition. But I am looking for better solution that has time complexity of O(n).

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
AJ.
  • 2,561
  • 9
  • 46
  • 81

1 Answers1

19

You can use "xor" operation on the entire array. Each pair of numbers will cancel each other, leaving you with the sought value.

int get_orphan(int const * a, int len)
{
    int value = 0;
    for (int i = 0; i < len; ++i)
        value ^= a[i];

    // `value` now contains the number that occurred odd number of times.
    // Retrieve its index in the array.
    for (int i = 0; i < len; ++i)
    {
        if (a[i] == value)
            return i;
    }

    return -1;
}
avakar
  • 32,009
  • 9
  • 68
  • 103