Missing Number
Easy
Topics
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing.
Example 1
The 3 values should be a permutation of
0..3, which sums to 6. They sum to 4, so the missing value is the difference, 2.Cells are the array values; the small numbers underneath are indices.
Input: nums = [3,0,1] Output: 2
Example 2
Input: nums = [0,1] Output: 2
Constraints
- n == nums.length
- 1 <= n <= 10^4
- All numbers are distinct and in [0, n].
Editorial — intuition, approach, complexity and pitfalls
Intuition
The full set 0..n has a known sum, n(n+1)/2. Subtract the sum of the array you were given, and the leftover is precisely the missing number.
Approach
- Compute the expected sum
n(n+1)/2forn = len(nums). - Subtract the actual array sum.
- Return the difference.
Walkthrough
nums = [3, 0, 1], n = 3
expected = 3*4/2 = 6
actual = 3+0+1 = 4
missing = 6 - 4 = 2Complexity
- Time — O(n): one pass to sum.
- Space — O(1): arithmetic only.
Common Pitfalls
- With huge n, the sum can overflow fixed-width ints — XOR of indices and values avoids that.
Full Solution — all languages
class Solution:
def missingNumber(self, nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)import java.util.*;
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length, sum = n * (n + 1) / 2;
for (int x : nums) sum -= x;
return sum;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int missingNumber(vector<int>& nums) {
int n = (int)nums.size(), sum = n * (n + 1) / 2;
for (int x : nums) sum -= x;
return sum;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var missingNumber = function(nums) {
const n = nums.length;
let sum = n * (n + 1) / 2;
for (const x of nums) sum -= x;
return sum;
};
Asked at
BlackRock