Missing Number
Easy · Bit manipulation
Jump to codeAn array of length n contains distinct integers chosen from 0 through n. Find the one value that is absent.
Examples
Example 1
nums = [3,0,1]
Output: 2
Example 2
nums = [0,1]
Output: 2
Constraints
- 1 <= nums.length <= 1000
Need a hint?
XOR cancels values that occur twice.
Asked in real interviews
Candidates reported versions of Missing Number from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Initialize an accumulator to n. For every index i, XOR both i and nums[i] into it. Every present value cancels its matching range value, leaving only the missing one. This avoids the overflow risk of adding the whole range in a fixed-width integer.
Complexity
O(n) time and O(1) space.
Python reference solution
def missingNumber(nums):
missing = len(nums)
for i, value in enumerate(nums):
missing ^= i ^ value
return missing
JavaScript solution
function missingNumber(nums) {
let missing = nums.length;
for (let i = 0; i < nums.length; i++) missing ^= i ^ nums[i];
return missing;
}
Java solution
import java.util.*;
class Solution {
public int missingNumber(int[] nums) {
int missing = nums.length;
for (int i = 0; i < nums.length; i++) missing ^= i ^ nums[i];
return missing;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = nums.size();
for (int i = 0; i < (int)nums.size(); i++) missing ^= i ^ nums[i];
return missing;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
0,
1
]
]2
[
[
0,
1
]
]2
[
[
9,
6,
4,
2,
3,
5,
7,
0,
1
]
]8
[
[
1,
2,
3
]
]0
[
[
0,
1,
2,
3
]
]4
Drafts are saved per language in this browser when storage is available.