arrays
bit-manipulation

Every value in nums appears exactly three times except for one value that appears exactly once. Return the value that appears once.

Input / output

  • Input: nums: int[]
  • Output: the unique integer

Examples

  1. nums = [2, 2, 3, 2] returns 3.
  2. nums = [0, 1, 0, 1, 0, 1, 99] returns 99.
  3. nums = [1, 1, 1, 2] returns 2.

Constraints

  • 1 <= nums.length <= 30000
  • -2^31 <= nums[i] <= 2^31 - 1
  • Every element appears exactly three times except one element that appears once.

Edge cases

  • Values can be negative.
  • The unique value may itself be 0.

Target complexity

  • Aim for O(n) time and O(1) extra space.

Hints

  1. Count how many times each bit position is set across all numbers.
  2. A bit that belongs to the unique number leaves a remainder of 1 when its count is taken modulo 3.

Follow-up Can you generalize the bit-counting trick for "every element appears k times except one"?

Examples

Example 1

Input: nums = [2,2,3,2]
Output: 3

Example 2

Input: nums = [0,1,0,1,0,1,99]
Output: 99

Example 3

Input: nums = [1,1,1,2]
Output: 2
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.