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) = 3
Returns (int) 2

Example 2

Input
nums (int[]) = [0,1]
size (int) = 2
Returns (int) 2

Example 3

Input
nums (int[]) = [9,6,4,2,3,5,7,0,1]
size (int) = 9
Returns (int) 8

The 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 - actualSum
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.