Learner Level

Implement the findMissingNumberFromOneToN method that finds the missing value from a sequence that should contain numbers from 1 to n.

The input contains an integer array nums, its length size, and a number n. The array contains numbers from 1 to n with exactly one number missing.

Your task is to find and return the missing number. For example, if nums = [1,2,4,5] and n = 5, the missing number is 3.

Example 1
Input:
nums (int[]) = [1,2,4,5]
size (int) = 4
n (int) = 5
Return:
(int) 3
Example 2
Input:
nums (int[]) = [2,3,4]
size (int) = 3
n (int) = 4
Return:
(int) 1
Example 3
Input:
nums (int[]) = [1]
size (int) = 1
n (int) = 2
Return:
(int) 2

The sum of numbers from 1 to n is known using the formula n * (n + 1) / 2.

Calculate the expected sum, subtract the actual sum of the array, and the remaining value is the missing number.

Pseudocode:

function findMissingNumberFromOneToN(nums, size, n):
    expectedSum = n * (n + 1) / 2
    actualSum = 0
    for each value in nums:
        actualSum = actualSum + value
    return expectedSum - actualSum
Run your code to see the result.