When elements in an array appear twice except one, we can simply XOR all numbers together. But what if every element appears three times, except for a single number that appears once?
The standard hash-map solution uses O(N) space. How can we solve this in O(N) time and O(1) space using digital logic gates (AND, OR, NOT, XOR) and a two-variable state machine (ones and twos)?
This problem is a masterpiece of digital circuit design translated into software code. Let’s design the state machine from first principles.
1. The Three States of a Bit
For any bit position, as we scan numbers in the array, how many times can we see a
1?To represent 3 distinct states (0, 1, and 2), we need 2 bits of memory! Let’s name them:
twos(the high bit)ones(the low bit)2. The Truth Table
When a new bit
xarrives from the current number:3. Deriving the Logic Gates
From the truth table:
ones = (ones ^ x) & (~twos)twos = (twos ^ x) & (~ones)When the full array has been scanned:
ones!Clean Python 3.12 Implementation
Complexity Breakdown
O(N). We touch each number once with 4 single-cycle bitwise operations.O(1). Exactly two integer variables living in registers.Here is the C++20 digital logic state machine for finding the unique number when all other numbers appear 3 times.
Complexity: Strictly
O(N)time andO(1)space (2 integer variables).