How would you find the element that appears exactly once in an array?

DSA
Easy
Microsoft
131.2K views

This classic problem tests knowledge of bitwise operations and hash map usage for frequency counting. It is a standard filter for technical proficiency.

Why Interviewers Ask This

Interviewers use this to quickly gauge a candidate's familiarity with XOR operations or hash maps. The XOR approach is particularly favored for its O(1) space complexity, demonstrating deep understanding of low-level bit manipulation properties. It separates candidates who memorize solutions from those who understand underlying mechanisms.

How to Answer This Question

First, mention the brute-force approach using nested loops or sorting, noting their inefficiencies. Then, introduce the Hash Map approach for O(n) time but O(n) space. Finally, present the optimal XOR solution, explaining the property that x XOR x equals 0 and x XOR 0 equals x. Walk through an example trace to show how duplicates cancel out leaving the unique element.

Key Points to Cover

  • XOR property: a ^ a = 0
  • O(1) space complexity requirement
  • Single pass iteration through array
  • Handling arrays with multiple duplicates

Sample Answer

The most efficient way to find the single non-duplicate element is using the XOR operation. Since XORing a number with itself results in zero, and XORing with zero returns the number, iterating through the entire array a…

Common Mistakes to Avoid

  • Forgetting that XOR works only if every other element appears twice
  • Using unnecessary extra space with hash maps
  • Misinterpreting the problem statement regarding duplicate counts

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 127 DSA questionsBrowse all 107 Microsoft questions