PPractick

DSA interview question

Single Number (Every Other Element Appears Twice)

Medium · Algorithms · Topics: array, bit manipulation

The problem

A wedding caterer counts RSVP cards: every guest sent two copies (one by mail, one online) except for one guest who sent only one. Given the list of guest IDs, find the one that appears once. A hash map of counts works, but the elegant answer uses the XOR operator: XOR-ing a number with itself gives 0 and XOR is order-independent, so XOR-ing the whole list cancels every pair and leaves only the single ID, in O(n) time and O(1) space.

Example: [4, 1, 2, 1, 2] → 4.

Function signature

int singleNumber(const vector<int>& nums);  // every value appears twice except one

Test cases

Input numsOutputExplanation
[2, 2, 1]1
[4, 1, 2, 1, 2]4Pairs don't need to be adjacent
[1]1
[-3, 7, -3]7Works for negative numbers too
[0, 5, 5]0The single value can be 0

(Confirm: exactly one value appears once and every other value appears exactly twice; O(1) extra space is expected.)

How interviewers phrase it

Clarifying questions to ask

  1. Does every other value appear exactly twice?
  2. Is O(1) extra space required?
  3. Can values be negative?

Follow-ups to expect

  1. "Why does XOR work?"
  2. "What are the other approaches?"
  3. "What if every other element appears three times?"
  4. "What if two elements appear once?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in