Missing Number (LeetCode 268): Solution and Explanation
An array holds n distinct numbers taken from the range 0 to n, so exactly one number in that range is absent. Find the missing number.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest correct approach puts every value into a hash set and then checks 0, 1, 2 and so on until a number is not found. It is linear time but needs O(n) extra space. Sorting and looking for the first index where nums[i] != i avoids the set but costs O(n log n).
A better idea is to compare what you have against what you should have. The complete range 0 to n is known in advance, so if you could combine all of it into one value, and combine all the array values the same way, the difference between the two would expose the missing number. Summation does this: the full range adds up to n × (n + 1) / 2, and subtracting the array's sum leaves the gap.
XOR does the same job with no risk of large intermediate values. Since a ^ a = 0 and XOR can be applied in any order, XORing every number from 0 to n together with every number in the array makes each present value appear twice and cancel out. The missing number appears only once, from the range side, so it is all that remains.
The reference code does this in two simple loops: one folds in the full range 0 through n, and the other folds in the array values. You could merge them into a single loop over indices, but the two-loop form makes the cancellation easier to see. Either way, the array is read once and never modified, which matters if the caller still needs it afterward.
Approach: XOR cancellation
- Let
n = len(nums)and start withxor = 0. - XOR every integer from 0 to n inclusive into
xor, which accounts for the complete range. - XOR every value in
numsintoxor, which cancels each number that is present. - Every present number has now appeared twice and vanished, and only the missing one is left.
- Return
xor.
Step-by-step example
nums = [3,0,1]
nis 3, so the full range is 0, 1, 2, 3.- Folding the range: 0 ^ 1 = 1, then 1 ^ 2 = 3, then 3 ^ 3 = 0. So
xoris 0 after the first loop. - Folding the array: 0 ^ 3 = 3, then 3 ^ 0 = 3, then 3 ^ 1 = 2.
- The values 0, 1 and 3 each appeared twice and cancelled, and 2 appeared only once.
- The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def missingNumber(self, nums: List[int]) -> int:
3 n = len(nums)
4 xor = 0
5
6 for i in range(n + 1):
7 xor ^= i
8
9 for num in nums:
10 xor ^= num
11
12 return xor1class Solution {
2 public int missingNumber(int[] nums) {
3 int n = nums.length;
4 int xor = 0;
5
6 for (int i = 0; i <= n; i++) {
7 xor ^= i;
8 }
9
10 for (int num : nums) {
11 xor ^= num;
12 }
13
14 return xor;
15 }
16}1class Solution {
2public:
3 int missingNumber(vector<int>& nums) {
4 int n = nums.size();
5 int xorVal = 0;
6
7 for (int i = 0; i <= n; i++) {
8 xorVal ^= i;
9 }
10
11 for (int num : nums) {
12 xorVal ^= num;
13 }
14
15 return xorVal;
16 }
17};Time and space complexity
O(n)
The first loop runs n + 1 times and the second runs n times, each with a single XOR.
O(1)
The only extra storage is the running xor value and the loop variables.
Other approaches
Gauss sum formula (time O(n), space O(1))
Compute the expected total n × (n + 1) // 2 and subtract sum(nums). It is just as fast and arguably easier to explain, but in fixed-width languages the expected sum can overflow for very large n, which XOR never does.
Hash set lookup (time O(n), space O(n))
Put all values in a set and return the first number from 0 to n that is not in it. It is the most obvious approach and generalizes to more missing values, but it uses linear extra memory.
Common mistakes
- Folding in only 0 to n - 1. When the missing number is n itself, as in [0,1], the answer would come out as 0 instead of 2.
- Using binary search on an unsorted array. The approach of checking
nums[mid] == midonly works after sorting. - Computing the expected sum with 32-bit integers in Java or C++ for very large n, which overflows. XOR or a 64-bit accumulator avoids this.
- Assuming 0 is always present and starting the range at 1. Zero can be the missing value, as in [1,2].
Frequently asked questions
How does XOR find the missing number?
XOR a value with itself and you get 0, and the order of XOR operations does not matter. XORing the full range with all array values cancels every number that appears in both, leaving only the missing one.
Is the sum formula or XOR better for Missing Number?
Both are O(n) time and O(1) space. The sum formula reads naturally, while XOR avoids any chance of integer overflow in languages with fixed-width integers.
Can Missing Number be solved in O(1) space?
Yes. Both the XOR approach and the sum formula use a constant number of variables and never modify the array.
What if more than one number is missing?
XOR alone no longer separates them. A hash set or an in-place marking pass, where each value flags its own index, finds every missing number in linear time.