Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Two values appear once and every other value twice. Find both (smaller first).

Problem: Two values appear once and every other value twice. Find both (smaller first).
def two_single(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_single([4, 1, 2, 1, 2, 7, 9, 9]))
What is printed?
  1. A. [3, 0]
  2. B. [4, 7]
  3. C. [1, 2]
  4. D. [4, 9]

Correct answer: B. [4, 7]

XOR of all = 4 ^ 7 = 3. Its lowest set bit (1) differs between the two answers, so splitting all values by that bit puts 4 and 7 in different groups, where pairs cancel. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic