Leetcode - Missing Number (with JavaScript)
Urfan Guliyev
Posted on July 20, 2020
Today I am going to show how to solve the Missing Number algorithm problem.
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:
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
};
💖 💪 🙅 🚩
Urfan Guliyev
Posted on July 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.