DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

Leetcode - Missing Number (with JavaScript)

Today I am going to show how to solve the Missing Number algorithm problem.

Here is the problem:
Alt Text

Solution:
I solved this problem in 2 different ways.

The first one is easier and simpler. I used a Set data structure to store an array. Then I iterate through it to find which number is missing.



var missingNumber = function(nums) {
    let map = new Set(nums);

    let expectedLength = nums.length + 1

    for (let number = 0; number < expectedLength; number++) {
        if (!map.has(number)) {
            return number
        }
    }

    return -1
};


Enter fullscreen mode Exit fullscreen mode

For the second solution I use Gauss' formula, which helps to sum sequences of numbers. You can see the formula below:
Alt Text

Essentially, all we have to do is to find the expected sum by using Gauss’ formula and then subtract from it the actual sum of the array.



var missingNumber = function(nums) {
    let expectedSum = nums.length*(nums.length + 1)/2
    let actualSum = nums.reduce((a, b) => a + b, 0)
    let missingNumber = expectedSum - actualSum

    return missingNumber 
};


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
lornawanjiru profile image
Lorna Wanjiru

Hey i would really appreciate if you could explain why you returned -1

Collapse
 
kylemit profile image
Kyle

Great solutions! Thanks!