Created
December 8, 2020 13:57
-
-
Save ali-master/a0f32f7bc3d24efaf800de6098cc51e9 to your computer and use it in GitHub Desktop.
Find missing number in an array of numbers
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
// Find theoretical sum of the consecutive numbers using a variation of Gauss Sum. | |
// Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2]; | |
// N is the upper bound and M is the lower bound | |
function missingNumber(n) { | |
let upperBound = 0; | |
let lowerBound = 99999999; | |
let sum = 0; | |
for (let i = 0; i < n.length; i++) { | |
sum += n[i]; | |
if(lowerBound > n[i]) lowerBound = n[i]; | |
if(n[i] > upperBound) upperBound = n[i]; | |
} | |
const upperBoundLimitSum = (upperBound * (upperBound + 1)) / 2; | |
const lowerBoundLimitSum = (lowerBound * (lowerBound - 1)) / 2; | |
const theoreticalBound = upperBoundLimitSum - lowerBoundLimitSum | |
return theoreticalBound - sum; | |
} | |
console.log(missingNumber([2, 5, 1, 4, 9, 6, 3, 7,10,11,12,13,14,15])) // 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awli