Missing Number
Missing Number is a easy bit manipulation problem solved with the missing / repeated numbers pattern.
The best approach, xor (no overflow), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, from sum formula up.
Problem
An array contains n distinct numbers taken from 0, 1, ..., n, so exactly one number in that range is missing. Find it.
Examples
Example 1
- Input
nums = [3, 0, 1]- Output
2
Example 2
- Input
nums = [0, 1]- Output
2- Why
- n = 2, so the range is 0..2.
Constraints
1 <= n <= 10^4; nums has n distinct values from 0..n.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Sum formula | O(n) | O(1) |
| XOR (no overflow) | O(n) | O(1) |
1Sum formula
O(n)Fine here; for very large n the sum can overflow, which XOR avoids.O(1)The full range sums to n(n + 1) / 2; subtract the actual sum.
- return n * (n + 1) / 2 - sum(nums).
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length, sum = 0;
for (int x : nums) sum += x;
return n * (n + 1) / 2 - sum;
}
}2XOR (no overflow)
O(n)O(1)XOR together 0..n and every value in nums. Each present value appears twice and cancels; the missing one remains.
- x = n; for i: x ^= i ^ nums[i].
class Solution {
public int missingNumber(int[] nums) {
int x = nums.length;
for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
return x;
}
}Edge cases to test
- The missing number is 0
- The missing number is n
Hints
Hint 1
XOR every index 0..n with every value. Everything present cancels out.
FAQ
What is the best time complexity for Missing Number?
XOR (no overflow) runs in O(n) time and O(1) extra space.
Which pattern does Missing Number use?
It is a bit manipulation problem that uses the missing / repeated numbers pattern. Other problems with the same pattern: Single Number, Two numbers with odd occurrences.
Is there a brute force solution for Missing Number?
Yes. Sum formula takes O(n) time and O(1) space. The full range sums to n(n + 1) / 2; subtract the actual sum.
Which edge cases should I test for Missing Number?
The missing number is 0; The missing number is n.