DSA AnimatorDSA animations
Single Number II LC #137 Medium Bit Count mod 3
Problem

Given an integer array nums where every element appears exactly three times except for one element which appears exactly once. Find the single element and return it. You must implement a solution with linear runtime and constant extra space.

Example 1
Input: nums = [2,2,3,2]
Output: 3
Explanation: 2 appears 3 times; 3 appears once.
Example 2
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Explanation: 99 appears once; others 3 times.
Constraints: 1 ≤ nums.length ≤ 3·10⁴ | Each element appears exactly 3 times except for one
Try Examples
Custom:
Input Array
Bit Counters (32-bit)
Variables
n (current)
—
ans
0
Step Logic
Press ▶ Play or Next Step to begin.
✅
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Initialize 32 counters to 0
2
For each number, add its bits to the counters
3
Take modulo 3 of each counter
4
Reconstruct the single number from remaining bits
Time
O(n)
Space
O(1)
Why It Works

By summing the bits of all numbers at each position, we count how many times each bit appears. Since every other number appears exactly 3 times, their bits contribute a multiple of 3 to the counters. Taking the modulo 3 of each counter effectively cancels out the numbers that appear 3 times, leaving only the bits of the single number!

How to solve Single Number II

LeetCode 137 · Medium · Bit Manipulation · Pattern: Bit Counting mod 3

Why the obvious approach is slow

XOR does not work here, because three copies do not cancel. A hash map works, but it uses extra space.

The key idea

Look at each bit position separately. Count how many numbers have a 1 in that position. Numbers appearing three times add a multiple of 3 to that count. So the count mod 3 is exactly the bit of the single number.

Remember

Count bits per position, mod the repeat count. The same trick works for any repeat count k.

Run the animation above on your own input, or watch the 1:22 video explanation of Single Number II with a dry run and Java code.

More Bit Manipulation problems