DSA interview question
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.
int singleNumber(const vector<int>& nums); // every value appears twice except one
Input nums | Output | Explanation |
|---|---|---|
[2, 2, 1] | 1 | |
[4, 1, 2, 1, 2] | 4 | Pairs don't need to be adjacent |
[1] | 1 | |
[-3, 7, -3] | 7 | Works for negative numbers too |
[0, 5, 5] | 0 | The single value can be 0 |
(Confirm: exactly one value appears once and every other value appears exactly twice; O(1) extra space is expected.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in