loading...

Leetcode - Missing Number (with JavaScript)

urfan profile image Urfan Guliyev ・1 min read

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
};

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 
};

Posted on by:

urfan profile

Urfan Guliyev

@urfan

Love coding, eating and travelling

Discussion

markdown guide