Algo-Sim › Matrix & Bit Manipulation
Single Number II
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Every number appears three times except one. Count the 1s in each bit column mod 3: the leftovers are the single number’s bits.
Problem
In the array nums, every value appears exactly three times except one, which appears once. Return that value, in linear time and constant extra space.
Constraints
- 1 ≤ nums.length ≤ 3 · 10⁴
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- O(n) time and O(1) extra space
Edge cases to test
- A negative single number (the sign bit)
- One element
- The single value is 0
Follow-up questions
- How does the ones/twos trick work?
- They hold the bits seen once and twice mod 3:
ones = (ones ^ x) & ~twos,twos = (twos ^ x) & ~ones. O(n), O(1). - How does it generalise?
- For values repeated k times, count each bit mod k: O(32·n) time, O(1) space.
Solution
Java
public int singleNumber(int[] nums) {
int result = 0;
for (int bit = 0; bit < 32; bit++) {
int count = 0;
for (int num : nums) count += (num >> bit) & 1;
// Triples add 0 mod 3; only the single number's bit is left over.
if (count % 3 != 0) result |= 1 << bit;
}
return result;
}Python
def single_number(nums):
result = 0
for bit in range(32):
count = sum((num >> bit) & 1 for num in nums)
# Triples add 0 mod 3; only the single number's bit is left over.
if count % 3:
result |= 1 << bit
# Python ints are unbounded: bit 31 set means a negative 32-bit answer.
return result - (1 << 32) if result >= 1 << 31 else resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int singleNumber(vector<int> &nums) {
unsigned result = 0;
for (int bit = 0; bit < 32; bit++) {
int count = 0;
for (int num : nums) count += (unsigned(num) >> bit) & 1;
// Triples add 0 mod 3; only the single number's bit is left over.
if (count % 3 != 0) result |= 1u << bit;
}
return int(result);
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)