DSA interview question
A warehouse scanner logs every item twice (once in, once out), and the log is sorted by item ID. Exactly one item was scanned only once, a sign it was lost, and it must be found in O(log n), since the log is huge. XOR would find it in O(n), but sortedness enables better. Before the single element, each pair starts at an even index (0, 2, 4, ...); after it, every pair starts at an odd index. Binary search on that parity pattern pinpoints where it breaks.
Example: [1, 1, 2, 3, 3, 4, 4, 8, 8] → 2.
int singleNonDuplicate(const vector<int>& nums); // sorted; every value appears twice except one
Input nums | Output | Explanation |
|---|---|---|
[1, 1, 2, 3, 3, 4, 4, 8, 8] | 2 | |
[3, 3, 7, 7, 10, 11, 11] | 10 | |
[1] | 1 | |
[1, 1, 2] | 2 | The single is last |
[1, 2, 2] | 1 | The single is first |
(Confirm: the array is sorted, has odd length, and every value appears exactly twice except one; O(log n) time and O(1) space.)
lo = mid + 2?"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