Problem Description
Given an integer array nums
where every element appears three times except for one, which appears exactly once. Find the single element and return it.
Key Insights
- The problem requires identifying a unique number in an array where all other numbers appear thrice.
- A naive approach using a hash map would not meet the constant space requirement.
- Bit manipulation can be leveraged to count the occurrences of bits in the numbers.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
To solve this problem, we can use bit manipulation. The idea is to count the number of times each bit (from the least significant to the most significant) appears across all numbers in the array. Since every number except one appears three times, the bits corresponding to numbers that appear three times will contribute to a count that is a multiple of three. The bits from the unique number will cause the count to differ from a multiple of three.
- We will create an array of size 32 (for each bit in a 32-bit integer) to count the occurrences of each bit.
- For each number, we will iterate through each bit and update our counts.
- After processing all numbers, we will check each bit count. If a count is not a multiple of three, it means that bit is set in the unique number.
- Finally, we will reconstruct the unique number from the bits that were found.