Algo-Sim › Matrix & Bit Manipulation
Single Number
Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Every number appears twice except one. XOR them all: pairs cancel to 0, leaving the single one, in O(1) space.
Problem
In the non-empty array nums, every value appears exactly twice except one, which appears once. Return that value, using linear time and constant extra space.
Constraints
- 1 ≤ nums.length ≤ 3 · 10⁴
- -3 · 10⁴ ≤ nums[i] ≤ 3 · 10⁴
- O(n) time and O(1) extra space (no hash set)
Edge cases to test
- One element
- Negative numbers (XOR works on two’s complement)
- The single value is 0
Follow-up questions
- What if the others appear three times?
- Count each bit mod 3, or keep
ones/twosbitmasks (LC 137): O(n), O(1). - What if two numbers appear once?
- XOR everything to get a ^ b, split by its lowest set bit, and XOR each group (LC 260).
Solution
Java
public int singleNumber(int[] nums) {
int x = 0;
for (int num : nums) {
x ^= num;
}
return x;
}Python
def single_number(nums):
x = 0
for num in nums:
x ^= num
return xC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int singleNumber(vector<int> &nums) {
int x = 0;
for (int num : nums) {
x ^= num;
}
return x;
}
};
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 II (Medium)
- 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)