CodingNodes / Bit Manipulation / Single Number II System design Space play · ←→ step · R restart

Problem

An array holds whole numbers. Every value appears exactly three times, except one value that appears exactly once. Return the value that appears once.

Numbers are ordinary 32-bit signed integers, so negatives are allowed. Use only a few extra variables.

The animation draws only the low 4 bits, because its examples are all below 16. The code still works on all 32 bits. The 28 higher bits are shown as one summary step.

Constraints

  • 1 ≤ nums.length ≤ 30000, and nums.length is 1 more than a multiple of 3
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • Exactly one value appears once; every other value appears three times

Examples: pick one to animate

Solutions

TimeO(32·n) SpaceO(1)

Time: For each of the 32 bit positions the loop looks at all n numbers once.

Space: Only the counters total and result, whatever n is.

Look at one bit position at a time. Add up that bit across all numbers. A value that appears three times contributes 0 or 3, which is 0 mod 3, so only the single number is left over. If the total mod 3 is 1, the single number has a 1 in that position. Set that bit in the result.