Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space.

Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space.
def two(a):
    x = 0
    for v in a: x ^= v
    low = x & -x
    p = q = 0
    for v in a:
        if v & low: p ^= v
        else: q ^= v
    return sorted((p, q))
print(*two([4, 1, 2, 1, 2, 3, 5, 5, 6, 6]))
What is printed?
  1. A. 4 7
  2. B. 1 3
  3. C. 3 4
  4. D. 3 5

Correct answer: C. 3 4

XOR of everything is 4 ^ 3 = 7; its lowest set bit (1) differs between the two singles. Splitting by that bit puts 1, 1, 3, 5, 5 in one group (XOR = 3) and 4, 2, 2, 6, 6 in the other (XOR = 4).

More Coding Interview Problems questions

Exams that ask this topic