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) =
4n (int) =
5Returns (int)
3Example 2
Input
nums (int[]) =
[2,3,4]size (int) =
3n (int) =
4Returns (int)
1Example 3
Input
nums (int[]) =
[1]size (int) =
1n (int) =
2Returns (int)
2The 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 - actualSumReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run