Single Number II
medium
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
nums = [2, 2, 3, 2]returns3.nums = [0, 1, 0, 1, 0, 1, 99]returns99.nums = [1, 1, 1, 2]returns2.
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 andO(1)extra space.
Hints
- Count how many times each bit position is set across all numbers.
- A bit that belongs to the unique number leaves a remainder of
1when its count is taken modulo3.
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.