Last active
February 15, 2020 18:23
-
-
Save iconifyit/6d43593d38723fcca48b6f1807c54022 to your computer and use it in GitHub Desktop.
30 Days of Algorithms : Find the missing number in an array of numbers 0 ... N
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This algorithm finds a missing number in an array of numbers from 1 - N. | |
* This approach only works if there is one-and-only-one missing number, | |
* and no duplicate numbers. There are other algorithms for those cases | |
* which I will cover on a different day. | |
* | |
* Given : a is a list of positive integers from 1 - N | |
* Given : a contains all unique numbers | |
* Given : a has one-and-only-one missing number | |
* Given : n == a.length | |
* | |
* @param {array} a An array of positive integers. | |
* @param {int} n The length of `a` | |
* @returns {number} | |
* @link https://github.com/iconifyit/30-Days-of-Algorithms | |
*/ | |
const findMissingNumber1toN = (a, n) => { | |
/* | |
* Calculate the sum of all numbers in the array. | |
*/ | |
let sum = a.reduce((a, v) => a + v); | |
/* | |
* Now calculate the maximum sum the array /could/ have with the missing | |
* number included then subtract the original sum. The result is the | |
* missing number. | |
*/ | |
return (n + 1) * (n + 2) / 2 - sum; | |
} | |
const a = [1, 2, 3, 5, 6]; | |
// --> Expected : 4 | |
console.log( | |
"Inputs : [" + a.join(', ') + "] \n" + | |
"Missing number : " + findMissingNumber1toN( a, a.length ) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment