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

Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space.

Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space.
def single(a):
    ones = twos = 0
    for x in a:
        ones = (ones ^ x) & ~twos
        twos = (twos ^ x) & ~ones
    return ones
print(single([5, 3, 5, 9, 5, 3, 3]), single([-2, -2, 1, -2]))
What is printed?
  1. A. 9 -2
  2. B. 14 1
  3. C. 9 1
  4. D. 0 1

Correct answer: C. 9 1

ones and twos form a per-bit counter modulo 3: a bit seen once lives in ones, twice in twos, and the third time clears both. Plain XOR of everything gives 5 ^ 3 ^ 9 here (three copies don't cancel). Works for negatives too. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic