Skip to problem
←

Missing Number

Easy 0 attempts

You're given an array nums holding n distinct integers, with every value falling somewhere in the inclusive range [0, n]. Out of all the integers in that range, exactly one does not appear in the array — figure out which one and return it.

The complete range spans n + 1 values, {0, 1, …, n}, while the array only holds n of them.

Function contract

Implement missingNumber(nums). Receive n distinct integers from the inclusive range 0 through n, where n is nums.length.

Output: Return the one missing integer. Input order does not matter.

Example 1

Input
nums = [3,0,1]
Output
2

Example 2

Input
nums = [0,1]
Output
2

Example 3

Input
nums = [9,6,4,2,3,5,7,0,1]
Output
8
Constraints
  • n == nums.length
  • 1 <= n <= 10^4
  • 0 <= nums[i] <= n
  • All numbers are unique

Expected Sum Minus Actual Sum

The complete range 0 through n sums to n(n + 1) / 2. Since the input contains each other value exactly once, subtracting its sum leaves the missing value. Neither sorting nor mutation is needed. Under n <= 10000, the expected sum is at most 50005000, exactly representable by JavaScript Number.

javascript
function missingNumber(nums) {
  const n = nums.length;
  return n * (n + 1) / 2 - nums.reduce((a, b) => a + b, 0);
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript