Question presented to candidate: "You get a non-empty list of integers in which every value appears exactly twice except one, which appears once. Write a Python function that returns that single value. Can you do it in linear time and constant extra space?"
What a strong answer should cover:
- The baseline answers first: nested scan O(nยฒ), a
dict/collections.Counterof counts O(n) time and O(n) space, sorting O(n log n). - XOR:
a ^ a == 0anda ^ 0 == a, and XOR is commutative and associative, so XOR-ing everything leaves the single number. - O(n) time, O(1) extra space, and why O(n) is the best possible.
- Python details:
^is XOR (power is**),functools.reduce(operator.xor, nums, 0)is the one-liner, and Python ints are unbounded so negatives behave like an infinite run of sign bits. - The follow-ups: three-times (count bits mod 3, then convert bit 31 back to a negative number in Python) and two singles (split on the lowest set bit).
Clarifying questions expected:
- Is it guaranteed that every other value appears exactly twice?
- Is O(n) extra memory allowed, or must it be O(1)?
Code / implementation expected: Yes โ a one-pass XOR function in Python 3, optionally with the Counter version for comparison.