DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

7 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay