One Pager Cheat Sheet
- Write a function
missingNumbersthat takes an array of continuous numbers and returns the missing integers inO(n)time withO(1)space complexity. - The key to finding the missing number in an array is to make sure that the array is sorted in ascending order, then check that each adjacent number is incrementing by
1, or use awhileloop toappendthe appropriate numbers. - This approach is harder to grok, however it can be optimized by iterating through both arrays
simultaneously, resulting in an O(n) runtime complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx50
}var assert = require('assert');​function missingNumbers(numArr) { let missing = [];​ for (let i = 1; i < numArr.length; i++) { // check where there are gaps if (numArr[i] - numArr[i - 1] != 1) { let x = numArr[i] - numArr[i - 1]; let diff = 1; while (diff < x) { missing.push(numArr[i - 1] + diff); diff++; } } }​ return missing;}​try { assert.deepEqual(missingNumbers([0, 1, 3]), [2]);​ console.log('PASSED: ' + 'missingNumbers([0, 1, 3]) should equal [2]');} catch (err) { console.log(err);}​try { assert.deepEqual(missingNumbers([10, 11, 14, 17]), [12, 13, 15, 16]);​ console.log(OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.

