Algo-Sim › Matrix & Bit Manipulation
Single Number III
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Two numbers appear once, the rest twice. XOR all gives a ^ b; its lowest set bit splits the array into two groups, each XORing to one single.
Problem
In the array nums, exactly two values appear once and every other value appears exactly twice. Return the two single values, in any order, using linear time and constant extra space.
Constraints
- 2 ≤ nums.length ≤ 3 · 10⁴
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- Exactly two values appear once
Edge cases to test
- The two singles are negative
- Exactly two elements
- One single is 0
Follow-up questions
- Why does the lowest set bit split them?
- a ^ b has a 1 where a and b differ; any such bit puts them in different groups, while each pair lands together.
- Is
x & −xsafe in Java and C++? - For
Integer.MIN_VALUEit overflows to itself, which is still its lowest bit. In C++ use unsigned orlong longto avoid undefined behaviour.
Solution
Java
public int[] singleNumber(int[] nums) {
int xor = 0;
for (int num : nums) xor ^= num;
// a ^ b != 0, so a and b differ at its lowest set bit.
int low = xor & -xor;
int[] out = new int[2];
for (int num : nums) {
if ((num & low) != 0) out[0] ^= num;
else out[1] ^= num;
}
return out;
}Python
def single_number(nums):
xor = 0
for num in nums:
xor ^= num
# a ^ b != 0, so a and b differ at its lowest set bit.
low = xor & -xor
out = [0, 0]
for num in nums:
if num & low:
out[0] ^= num
else:
out[1] ^= num
return outC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int> &nums) {
unsigned x = 0;
for (int num : nums) x ^= num;
// a ^ b != 0, so a and b differ at its lowest set bit.
unsigned low = x & -x;
vector<int> out(2);
for (int num : nums) {
if (num & low) out[0] ^= num;
else out[1] ^= num;
}
return out;
}
};
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 II (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)