Learner Level
Implement the missingNumberZeroToN method that finds the missing number from the range 0 to n.
The input contains an array nums with size numbers. The array contains distinct values from the range 0 to size, but exactly one number from that range is missing.
Your task is to return the missing number. For example, in [3,0,1], the range should be 0 to 3, and the missing value is 2.
Example 1
Input
nums (int[]) =
[3,0,1]size (int) =
3Returns (int)
2Example 2
Input
nums (int[]) =
[0,1]size (int) =
2Returns (int)
2Example 3
Input
nums (int[]) =
[9,6,4,2,3,5,7,0,1]size (int) =
9Returns (int)
8The numbers should normally contain every value from 0 to size.
Calculate the expected sum of that full range using the formula size * (size + 1) / 2. Then subtract the actual sum of the given array.
The difference between the expected sum and the actual sum is the missing number.
Pseudocode:
function missingNumberZeroToN(nums, size):
expectedSum = size * (size + 1) / 2
actualSum = 0
for each num in nums:
actualSum = actualSum + num
return expectedSum - actualSumReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run