-
-
Save kdncode/07580999bc94f00c4f7cae9f24fd6c1e to your computer and use it in GitHub Desktop.
How to find the missing numbers from an array of integers. Q: You’re given an array of N integers. N may be very large. You know that every integer 1-N appears once in the array, except there is one or more integer(s) missing.
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
/* ============================ | |
* EXAMPLE 1: | |
* ============================ */ | |
var numbers = [0,1,3,4,5,7,8]; // Missing 2,6 | |
var lastNumber = numbers[numbers.length - 1]; | |
var expectedSum = (lastNumber * (lastNumber + 1)) / 2; | |
var actualSum = 0; | |
// Show the difference | |
for (var i = 0; i < numbers.length; i++) { | |
actualSum += numbers[i]; | |
} | |
console.log(expectedSum - actualSum); | |
/* ============================ | |
* EXAMPLE 2: | |
* ============================ */ | |
var numbers = [0,1,3,4,5,7,8]; // Missing 2,6 | |
var missing = []; | |
// Find the missing array items | |
for ( var i = 0; i < numbers.length; i++ ) { | |
if ( (numbers[i+1] - numbers[i]) > 1 ) { | |
missing.push( numbers[i+1] - numbers[1] ); | |
} | |
} | |
console.log( missing ); | |
/* ============================ | |
* EXAMPLE 3: | |
* ============================ */ | |
var intArray = [9,1,5,8,7,4,3,0,10,13,15,19,12,16,18]; // Missing 2,6,11,14,17 | |
var arrayLength = Math.max.apply(Math, intArray); | |
var missing = [] | |
for ( var i = 0; i < arrayLength; i++ ) { | |
if ( intArray.indexOf(i) < 0 ) { | |
missing.push( i ); | |
} | |
} | |
console.log( missing ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment