Once Twice Problem
Description
LeetCode Problem 3595.
You are given an integer array nums. In this array:
- Exactly one element appears once.
- Exactly one element appears twice.
- All other elements appear exactly three times.
Return an integer array of length 2, where the first element is the one that appears once, and the second is the one that appears twice.
Your solution must run in O(n) time and O(1) space.
Example 1:
Input: nums = [2,2,3,2,5,5,5,7,7]
Output: [3,7]
Explanation:
The element 3 appears once, and the element 7 appears twice. The remaining elements each appear three times.
Example 2:
Input: nums = [4,4,6,4,9,9,9,6,8]
Output: [8,6]
Explanation:
The element 8 appears once, and the element 6 appears twice. The remaining elements each appear three times.
Constraints:
3 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 1nums.lengthis a multiple of 3.- Exactly one element appears once, one element appears twice, and all other elements appear three times.
Solution
Approach: Bit Counts Modulo 3 + Split by One Bit
Count, for each bit position, how many numbers have it set. The triplets contribute multiples of 3, so the count mod 3 is a + 2b where a and b are that bit of the once-number and the twice-number. A count that is not a multiple of 3 means the two numbers differ in that bit (a count of 0 can also mean both bits are 1, so it tells us nothing). Since the two numbers are different, such a bit p exists.
Split the array by bit p. Now the once-number and the twice-number are in different groups. In each group every other number appears three times, so counting bits mod 3 again gives: a remainder of 1 means that bit belongs to the once-number, a remainder of 2 means it belongs to the twice-number. Collect both from the two groups.
Complexity: O(n) time (about 64 passes over the bits) and O(1) extra space.
class Solution:
def onceTwice(self, nums: List[int]) -> List[int]:
mask = 0xFFFFFFFF
total = [0] * 32
for x in nums:
x &= mask
for i in range(32):
total[i] += x >> i & 1
# the two special values differ in some bit, so that bit's count is not a multiple of 3
p = next(i for i in range(32) if total[i] % 3)
cnt = [[0] * 32, [0] * 32]
for x in nums:
x &= mask
g = x >> p & 1
for i in range(32):
cnt[g][i] += x >> i & 1
a = b = 0
for g in range(2):
for i in range(32):
if cnt[g][i] % 3 == 1:
a |= 1 << i
elif cnt[g][i] % 3 == 2:
b |= 1 << i
if a >= 1 << 31:
a -= 1 << 32
if b >= 1 << 31:
b -= 1 << 32
return [a, b]