Skip to content

Instantly share code, notes, and snippets.

@adyngom
Created September 7, 2017 07:24
Show Gist options
  • Save adyngom/4cde4dfad0705efa9bbb4893e53d11fa to your computer and use it in GitHub Desktop.
Save adyngom/4cde4dfad0705efa9bbb4893e53d11fa to your computer and use it in GitHub Desktop.
var findMissingNumber = function(arr) {
let size = arr.length;
console.log(size);
if(!size) {
return false;
}
// could sort the array first and get
// first and last index
// not sure which one would be faster
//let lower = Math.min.apply(null, arr);
let upper = Math.max.apply(null,arr);
// Using Gauss Sum: S = ( upper * (upper + 1) ) / 2;
let expectedSum = ( upper * (upper + 1) ) / 2;
//let lowerSum = (lower * (lower - 1)) / 2;
console.log(expectedSum);
let currentSum = arr.reduce( (a,c) => a + c, 0 );
console.log(currentSum);
let missingNumber = expectedSum - currentSum;
return missingNumber;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment