6. Find the Missing Number

EasyArrayArray

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Input: An integer array nums of length n with distinct values from 0 to n (one missing).

Output: A single integer — the missing number.

Examples

Example 1
Input: [3,0,1]
Output: 2
Explanation: n=3. Expected sum=0+1+2+3=6. Actual sum=3+0+1=4. Missing = 6-4 = 2.
Example 2
Input: [0,1]
Output: 2
Explanation: n=2. Expected sum=0+1+2=3. Actual sum=0+1=1. Missing = 3-1 = 2.
Example 3
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n=9. Expected sum=45. Actual sum=37. Missing = 45-37 = 8.

Constraints

Asked by

HCLTechAmazonBloombergMicrosoftGoogleIBM
Solve this problem in the editor →