Missing Number
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.
Input Format
Implement missingNumber(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 · Run Sample
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
Test Cases (3)
Case 1
Args: [[3,0,1]]
Expected: 2
Case 2
Args: [[0,1]]
Expected: 2
Case 3
Args: [[9,6,4,2,3,5,7,0,1]]
Expected: 8
XOR or Math
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)
Saved in this browser only. Private to you.