Single Number II

Given an integer array nums where every element appears exactly three times except for one element, which appears exactly once, find that single element and return it. The solution must run in linear time and use only constant extra space.

30:00

Single Number II
medium
Free written solution
Topics
Companies

Given an integer array nums where every element appears exactly three times except for one element, which appears exactly once, find that single element and return it. The solution must run in linear time and use only constant extra space.

Example 1:
Input: {"nums":[2,2,3,2]}
Output: 3
Constraints:
  • 1≤nums.length≤3×1041 \leq \text{nums.length} \leq 3 \times 10^4

  • −231≤nums[i]≤231−1-2^{31} \leq \text{nums}[i] \leq 2^{31} - 1

  • Each element in nums appears exactly three times except for one element which appears once.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[2,2,3,2]}

Every bit column counts how many 1s it has seen, modulo 3. Two registers hold that count: a bit in ones means count 1, a bit in twos means count 2.

nums in binary (4 bits)

bit 3 ... bit 0

2
0
0
1
0
2
0
0
1
0
3
0
0
1
1
2
0
0
1
0

Per-column count of 1s, mod 3

ones
0
0
0
0
twos
0
0
0
0
count
0
0
0
0

ones bit = count 1

twos bit = count 2

third hit resets to 0

ones = 0
twos = 0
Variables
VariableValue
ones0
twos0
DepthFunction Call
Stack empty
0/10