PPractick

DSA interview question

Single Element in a Sorted Array

Medium · Algorithms · Topics: binary search, array

The problem

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.

Function signature

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

Test cases

Input numsOutputExplanation
[1, 1, 2, 3, 3, 4, 4, 8, 8]2
[3, 3, 7, 7, 10, 11, 11]10
[1]1
[1, 1, 2]2The single is last
[1, 2, 2]1The 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the array sorted?
  2. Does every other value appear exactly twice?
  3. Is O(log n) required? (Otherwise XOR is simpler.)

Follow-ups to expect

  1. "What property are you searching on?"
  2. "Why force mid to be even?"
  3. "Why lo = mid + 2?"
  4. "Why does the length have to be odd?"
  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