← Back to Algorithms, page 5

algorithms-0098 · Hard senior

Single number when every other value appears three times: find the one value that appears once in O(n) time and O(1) extra space.

XOR alone fails because three copies do not cancel. Count each bit position modulo 3: the bits left over belong to the single number. Two integers can hold that counter for all 32 positions at once: ones and twos, updated with ones = (ones ^ v) & ~twos and twos = (twos ^ v) & ~ones. At the end ones holds the answer. O(n) time, O(1) space.

Full answer

Problem

In nums, every value appears exactly three times except one, which appears once. Return that value using O(1) extra space.

Example: [2, 2, 3, 2] returns 3; [0, 1, 0, 1, 0, 1, 99] returns 99; negative values must work too.

Constraints: up to 3 * 10^4 numbers; values are 32-bit signed integers.

Brute force

Count occurrences with a hash map and return the value with count 1: O(n) time but O(n) space. Sorting and scanning in groups of three is O(n log n).

Optimal approach

Per-bit counting: for each bit position b in 0..31, sum the b-th bits of all numbers; if the sum mod 3 is 1, set bit b in the answer. Convert from 32-bit two's complement at the end. O(32n).

Bit state machine: keep ones and twos.

  • ones = (ones ^ v) & ~twos
  • twos = (twos ^ v) & ~ones

After all values, ones is the answer.

Why it works

For each bit position, the bits of the triple values contribute a multiple of 3, so the count modulo 3 equals that bit of the single value. The state machine tracks that count per bit: a bit is in ones when its count is 1 mod 3 and in twos when it is 2 mod 3. On a new 1 bit the state moves 0 to 1 to 2 to 0: the first line adds the bit to ones unless it is already in twos; the second adds it to twos only if it just left ones; a third occurrence clears both. All 32 positions update in parallel with word operations. In Python, negative numbers behave as infinitely sign-extended, and the same identities hold, so ones comes out with the right sign.

Complexity

O(n) time and O(1) space for the state machine; O(32n) for per-bit counting.

Code

python
import random
from collections import Counter


def single_number_thrice(nums):
    """Every value appears three times except one, which appears once. O(n) time, O(1) space.
    `ones` holds bits seen 1 (mod 3) times, `twos` bits seen 2 (mod 3) times."""
    ones = twos = 0
    for v in nums:
        ones = (ones ^ v) & ~twos
        twos = (twos ^ v) & ~ones
    return ones


def single_number_bitcount(nums):
    """Per-bit counting mod 3 over 32 bits, then convert back from two's complement."""
    out = 0
    for b in range(32):
        if sum((v >> b) & 1 for v in nums) % 3:
            out |= 1 << b
    return out - (1 << 32) if out >= 1 << 31 else out


def brute(nums):
    return next(v for v, c in Counter(nums).items() if c == 1)


if __name__ == "__main__":
    assert single_number_thrice([2, 2, 3, 2]) == 3
    assert single_number_thrice([0, 1, 0, 1, 0, 1, 99]) == 99
    assert single_number_thrice([-2, -2, 1, 1, 4, 1, 4, 4, -5, -2]) == -5   # negatives work too
    rng = random.Random(98)
    for _ in range(1000):
        vals = rng.sample(range(-1000, 1000), rng.randint(1, 8))
        nums = [vals[0]] + [v for v in vals[1:] for _ in range(3)]
        rng.shuffle(nums)
        assert single_number_thrice(nums) == single_number_bitcount(nums) == brute(nums)
    print("all tests passed")

Save as b98_single_number_thrice.py and run python3 b98_single_number_thrice.py. It prints all tests passed (Python 3.13.5).

Edge cases

The single value is negative or zero. Only one element. Values at 32-bit limits (per-bit counting needs the two's complement fix in Python; the state machine does not). If the problem changes to "appears twice" for the single, return twos instead.

Pattern

Counting bits modulo k with a small state machine encoded in words. The general rule works for any k with ceil(log2 k) state words. Related: single number with all others appearing twice (XOR), two singles (XOR then split by a set bit), and bitwise digital-logic design of counters.

python
import random
from collections import Counter


def single_number_thrice(nums):
    """Every value appears three times except one, which appears once. O(n) time, O(1) space.
    `ones` holds bits seen 1 (mod 3) times, `twos` bits seen 2 (mod 3) times."""
    ones = twos = 0
    for v in nums:
        ones = (ones ^ v) & ~twos
        twos = (twos ^ v) & ~ones
    return ones


def single_number_bitcount(nums):
    """Per-bit counting mod 3 over 32 bits, then convert back from two's complement."""
    out = 0
    for b in range(32):
        if sum((v >> b) & 1 for v in nums) % 3:
            out |= 1 << b
    return out - (1 << 32) if out >= 1 << 31 else out


def brute(nums):
    return next(v for v, c in Counter(nums).items() if c == 1)


if __name__ == "__main__":
    assert single_number_thrice([2, 2, 3, 2]) == 3
    assert single_number_thrice([0, 1, 0, 1, 0, 1, 99]) == 99
    assert single_number_thrice([-2, -2, 1, 1, 4, 1, 4, 4, -5, -2]) == -5   # negatives work too
    rng = random.Random(98)
    for _ in range(1000):
        vals = rng.sample(range(-1000, 1000), rng.randint(1, 8))
        nums = [vals[0]] + [v for v in vals[1:] for _ in range(3)]
        rng.shuffle(nums)
        assert single_number_thrice(nums) == single_number_bitcount(nums) == brute(nums)
    print("all tests passed")

Two-word state machine and per-bit counting mod 3, cross-checked against a Counter on random inputs that include negatives.

Complexity

Time: O(n). Space: O(1). Per-bit counting is O(32n) and needs a 32-bit sign correction in Python.

By level

Fresher: Explains why XOR fails and counts each bit position modulo 3 to rebuild the answer. Handles the sign for negative values.

Mid: Implements the ones and twos state machine and explains the transitions per bit. Generalizes the counting idea to k repetitions.

Senior: Derives state machine formulas from truth tables, and discusses readability trade-offs of compact bit tricks versus per-bit counting in shared code. Documents the invariant next to the code so reviewers can verify it.

Key points

  • XOR fails when copies come in threes
  • Each bit's count mod 3 gives the single's bit
  • ones and twos encode the count per bit
  • All 32 positions update together
  • Works for negatives

Common mistakes

  • Trying plain XOR
  • Forgetting the sign fix in the per-bit version
  • Swapping the update order of ones and twos
  • Using a hash map when O(1) space is required

Follow-ups

  • Generalize to every other value appearing k times
  • How do you find two values that each appear once while others appear twice?
  • How would you derive the update formulas from a truth table?

Tips

  • Start with the per-bit counting idea
  • Then show the state machine as an optimization
  • Test a negative single value

Evaluation rubric

  • Correct per-bit idea
  • Correct state machine or counting
  • Handles negatives
  • O(1) space