DSA interview question
An inventory audit scans every item twice (once in, once out), except that two items were only scanned once. Find both of those IDs, in increasing order, in linear time and O(1) extra space. XOR-ing everything leaves a ^ b, which isn't either answer directly. But a ^ b isn't zero, so some bit differs between a and b. Splitting all numbers by that bit puts a and b in different groups, while each pair stays together, so XOR-ing each group gives a and b separately.
Example: [1, 2, 1, 3, 2, 5] → [3, 5].
vector<int> singleNumber(const vector<int>& nums); // the two unique values, ascending
| Input | Output | Explanation |
|---|---|---|
[1, 2, 1, 3, 2, 5] | [3, 5] | |
[-1, 0] | [-1, 0] | |
[0, 1] | [0, 1] | |
[2, 1, 2, 4] | [1, 4] | |
[7, 7, -8, 8] | [-8, 8] | They differ in the sign bit and more |
(Confirm: exactly two values appear once and all others exactly twice; the two answers are distinct; output in increasing order.)
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