Skip to content
Preptima
mediumCodingConceptEntryMidSenior

Every number in the array appears three times except one. Find the single number in O(1) extra space, and make sure it works for negatives.

Count, for each of the 32 bit positions, how many numbers have that bit set, and keep the count modulo 3. Tripled values contribute multiples of 3, so the bits with a remainder belong to the single number. Setting bit 31 makes a Java int negative, so negative answers come out right in O(32n) time and constant space.

5 min readUpdated 2026-10-09Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Use bit counting by position. For each of the 32 bit positions, count how many numbers have that bit set and take the count modulo 3. Every value that appears three times adds 0 or 3 to each position, so whatever remains is the single number's bit. In Java, setting bit 31 of an int makes it negative, which is exactly how two's complement represents a negative answer, so no sign fix-up is needed.

Was this answer helpful?

Likely follow-ups

  • The unique value appears twice instead of once. Which of your two solutions still works, and why does the other return 0?
  • Every value appears five times except one. What changes in the code and in the cost?
  • Why is O(32n) honestly constant space but a misleading description of time for small arrays?
  • How would you solve this for 64-bit values, and what goes wrong if the shift literal is still an int?

Related questions