InterviewPrepKit

Home / Coding / Bit Manipulation

Single Number II

medium Original β†—
Solving tips
  • Reason one bit column at a time: numbers appearing 3x contribute 0 or 3 ones to a column, so column_sum % 3 gives exactly the lone number's bit at that position.
  • Sum the ones at each of 32 positions, take mod 3, and reassemble, O(32n)=O(n) time, O(1) space.
  • Handle the sign bit: if bit 31 survives, the answer is negative, so subtract 2^31 (Python ints are arbitrary precision and won't do this for you).
  • Slicker single pass: the ones/twos state machine (ones = (ones ^ num) & ~twos; twos = (twos ^ num) & ~ones) cycles each bit 0->1->2->0; order matters, update ones before twos.

Problem

You are given an integer array nums in which every element appears exactly three times, except for one element that appears exactly once. Return that single element.

You must do it in linear time and using only constant extra space β€” no hash map of counts, no extra array proportional to the input.

Examples

  • nums = [2, 2, 3, 2] β†’ 3 2 appears three times; 3 is the lone element.
  • nums = [0, 1, 0, 1, 0, 1, 99] β†’ 99 0 and 1 each appear three times; 99 appears once.
  • nums = [-2, -2, 1, 1, -2, 1, 5] β†’ 5 Negatives are allowed; -2 and 1 each appear three times, 5 is alone.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1 (values can be negative; assume 32-bit integers).
  • Every element appears exactly three times except one, which appears exactly once β€” the input is guaranteed to have this shape.
  • Target complexity: O(n) time, O(1) space.

Think about it first

Hint 1 The easy O(n)-space answer is a frequency count β€” a hash map, or sum-of-unique tricks. The real challenge is dropping to O(1) space. Stop thinking about the numbers as whole values and think about them one *bit* at a time.
Hint 2 Look at a single bit position across the whole array. Every number that appears three times contributes that bit either 0 or 3 times. The lone number contributes it 0 or 1 more. So the total count of 1s at that position is `3k` or `3k + 1` β€” its value mod 3 reveals the lone number's bit.
Hint 3 Sum the 1-bits at each of the 32 positions, take each sum mod 3, and reassemble β€” that's O(32n) = O(n) time, O(1) space. Careful with the sign bit (position 31): a set bit there means the answer is negative. There is also a slicker two-variable "ones/twos" state machine that does it in a single pass.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.