Problem Description
Given an integer array nums where every element appears three times except for one which appears exactly once, find and return that single element. The solution must run in linear time and utilize constant extra space.
Key Insights
- Use bit manipulation to solve the problem in O(n) time with O(1) extra space.
- The core idea is to track the bit counts across all numbers and use modulo operations to cancel out bits that appear three times.
- Instead of using extra arrays for bit counts, maintain two accumulator variables to represent bits seen once and twice.
- Leverage bitwise XOR, AND, and NOT operations to update and clear bits accordingly.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The approach uses two accumulators, named ones and twos, to track the bits that have appeared once and twice, respectively. For each number in the array, we update these accumulators:
- Calculate new values for ones by XOR-ing with the current number and removing any bits that are already in twos.
- Update twos accordingly using bits that appear and are not newly reintroduced into ones. After processing all numbers, the variable ones will contain the unique single number because the bits corresponding to numbers that appear three times cancel out.