Single Number solution explained
To find the one value that appears once when every other value appears exactly twice, XOR all the numbers together. Equal values cancel because a XOR a is 0, zero changes nothing because a XOR 0 is a, and XOR does not care about order, so whatever remains is the lone value. The Single Number solution runs in O(n) time with O(1) extra space.
By Evin JohnPublished 6 min read
The task, restated
You get a non-empty list of integers. Every value in it shows up exactly two times, except one value that shows up only once. Return that value. The usual constraint is the interesting part: do it in a single linear pass, without memory that grows with the input.
| Input | Output |
|---|---|
| [12, 5, 9, 5, 12] | 9 |
| [7, 3, 7] | 3 |
| [6, -8, 6] | -8 |
| [-3] | -3 |
| [0] | 0 |
Confirm that the duplicates appear exactly twice, not "at least twice", and that exactly one value is unpaired. Both XOR and the counting approach depend on those promises.
How interviewers use it
Single Number is a quick screen for whether you know bitwise operators and can justify why a trick is correct. Most candidates reach the hash-map answer. The constant-memory requirement is there to see if you know, or can reason your way to, XOR's cancellation property. Interviewers then often stretch it into a family of variations.
- Every value appears three times except one. XOR no longer cancels. Count how many numbers have each bit set; a count not divisible by 3 means the single value has that bit. O(32·n) time, O(1) space.
- Two values appear once, the rest twice. XOR everything to get a XOR b, pick any set bit of that result (it differs between a and b), and split the list by that bit into two XOR runs.
- Find the missing number in 0 to n. XOR every index and every value; the missing one is left.
- The list is sorted. Binary search on pair alignment finds the single value in O(log n).
Brute force: count every value
Count occurrences in a dictionary, then return the key with a count of one. That is O(n) time and O(n) extra space. Sorting and scanning in pairs is another option, O(n log n) time with little extra memory if the sort is in place. Comparing each element against all others is O(n²) and only worth mentioning to dismiss it.
def single_by_count(nums):
counts = {}
for v in nums:
counts[v] = counts.get(v, 0) + 1
for v, k in counts.items():
if k == 1:
return vThe efficient approach: XOR everything
Exclusive or, written ^ in Python and JavaScript, compares two numbers bit by bit and sets a result bit only where the inputs differ. Three facts make it perfect here. A value XORed with itself is 0, because no bits differ. A value XORed with 0 is the value. And XOR is commutative and associative, so the order of the list does not matter. Fold the whole list with XOR: each pair collapses to 0 wherever its two copies sit, and the lone value is all that remains.
Walk through [12, 5, 9, 5, 12]: 12 ^ 5 ^ 9 ^ 5 ^ 12 can be regrouped as (12 ^ 12) ^ (5 ^ 5) ^ 9, which is 0 ^ 0 ^ 9, which is 9.
def single_number(nums):
result = 0
for v in nums:
result ^= v
return resultfunction singleNumber(nums) {
let result = 0;
for (const v of nums) result ^= v;
return result;
}A JavaScript note worth saying aloud: ^ converts its operands to 32-bit signed integers. That is fine for the usual input range, but values beyond about 2.1 billion in size would be truncated. Python's integers have no such limit, and negative numbers XOR correctly in both languages within that range.
Time and space
| Version | Time | Extra space |
|---|---|---|
| Compare every pair | O(n²) | O(1) |
| Sort, then scan in pairs | O(n log n) | O(1) to O(n), depending on the sort |
| Hash map of counts | O(n) | O(n) |
| Sum trick: 2 · sum(set) - sum(list) | O(n) | O(n) for the set |
| XOR fold | O(n) | O(1) |
Edge cases
- A single-element list: the answer is that element.
- The single value is 0, which XOR still returns correctly.
- Negative values.
- The single value at the very start or the very end.
- Inputs that break the promise (a value appearing three times). XOR then returns something meaningless; mention that you are trusting the constraint.
Mistakes to avoid
- Starting the fold at the first element and then XORing it again in the loop, which cancels it.
- Using OR or AND by mistake; only XOR cancels pairs.
- Applying XOR to the "three times" version, where it does not work.
- Claiming the sum trick uses constant memory; building the set does not.
- Not explaining why XOR works, which leaves the interviewer unsure you could adapt it.
How to explain it out loud
Fictional example
- Candidate
- A hash map of counts works in linear time but linear space. For constant space I want an operation where two equal values cancel.
- Candidate
- XOR does that: a XOR a is zero, a XOR zero is a, and order does not matter, so XORing the whole list leaves only the unpaired number.
- Candidate
- One pass, constant space. If values could appear three times I would switch to counting bits modulo three instead.
Related walkthroughs
Pow(x, n) is the other problem in this set where looking at the binary form of a number gives the efficient answer. Happy Number shares the quick math-puzzle feel. Meeting Rooms II has its own kind of cancellation: every meeting start is eventually matched by an end. And Two Sum is the classic hash-map answer for comparison.
Where Natively fits
Practicing on your Mac or Windows PC, you can have Natively read a short bit-manipulation problem from a screenshot and ask it for a hint toward XOR rather than the full answer. It also transcribes your mock round, so you can check that you explained why pairs cancel instead of simply stating the trick. More on the AI interview assistant.
Questions people ask
How do you find the number that appears once?
XOR all the values together. Each pair cancels to zero, zero leaves a value unchanged, and order does not matter, so the result is the unpaired value.
Why does XOR work for Single Number?
Because a XOR a is 0, a XOR 0 is a, and XOR is commutative and associative. Every duplicate meets its twin and disappears.
What is the time and space complexity of Single Number?
O(n) time and O(1) extra space with XOR. A hash map of counts is also O(n) time but needs O(n) space.
What if every other number appears three times?
XOR no longer cancels. Count how many values have each bit set and keep the bits whose count is not a multiple of three.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
