Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created December 8, 2020 13:57
Show Gist options
  • Save ali-master/a0f32f7bc3d24efaf800de6098cc51e9 to your computer and use it in GitHub Desktop.
Save ali-master/a0f32f7bc3d24efaf800de6098cc51e9 to your computer and use it in GitHub Desktop.
Find missing number in an array of numbers
// 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
@pooooriya
Copy link

awli

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment