Algo-Sim › Matrix & Bit Manipulation
Missing Number
Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
n distinct numbers from 0..n, one missing. XOR the indices, the values and n: everything present cancels in pairs.
Problem
The array nums holds n distinct numbers taken from the range 0..n, so exactly one number of that range is missing. Return it.
Constraints
- 1 ≤ n ≤ 10⁴ (n = nums.length)
- 0 ≤ nums[i] ≤ n, all distinct
- Follow-up: O(1) extra space and O(n) time
Edge cases to test
- Missing 0
- Missing n
- One element
Follow-up questions
- What about the sum formula?
n(n + 1)/2 − sumworks but can overflow 32 bits for big n; XOR can’t overflow.- What if two numbers are missing?
- XOR gives a ^ b; split by its lowest set bit as in Single Number III. Or use the sum and the sum of squares.
Solution
Java
public int missingNumber(int[] nums) {
int missing = nums.length;
for (int i = 0; i < nums.length; i++) {
missing ^= i ^ nums[i];
}
return missing;
}Python
def missing_number(nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missingC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = int(nums.size());
for (int i = 0; i < int(nums.size()); i++) {
missing ^= i ^ nums[i];
}
return missing;
}
};
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)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)