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

Example 2

Input
nums (int[]) = [2,3,4]
size (int) = 3
n (int) = 4
Returns (int) 1

Example 3

Input
nums (int[]) = [1]
size (int) = 1
n (int) = 2
Returns (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
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.