Skip to the solution
EasyDSA12 min read

How do you find the single number where every other element appears twice?

331 views

The problem

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.Counter of counts O(n) time and O(n) space, sorting O(n log n).
  • XOR: a ^ a == 0 and a ^ 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.

  • arrays
  • bit-manipulation

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

Pythonsingle_number with XOR, plus a trace of the running value
PythonBrute force vs dict vs sort vs sum vs XOR, with work counters
PythonFollow-ups: every other value three times, and two single values

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 31 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you merge two sorted arrays?

Continue