need to consider 2 equation s sum of numbers and sum of squares

iterate through array from first to last element and store minimum, maximum and sum as you go. Then take max - min to check if the missing integers are internal or external. If max - min = n -3 then both the missing numbers are the end points. If max - min = n-2 then one missing number is an endpoint, though it would be impossible to determine from which end. If max - min = n-1 then both numbers are consecutive. This should be the most probable result unless n is quite small. We then take the sum of all numbers in the array (which we stored) and from it subtract [(max + min ) * n], which is the sum of all numbers from min to max (including missing numbers). This gives you the sum of the two missing numbers (or one missing number if the other one is external). You have one equation with two unknowns. For the second equation you have several options. Ivan pointed out that the sum of squares will yield a second equation for the same two unknowns.

function findMissing2(numbers) { var missing = []; var delta; var currentNumber; numbers.sort(function(a,b){ return a - b; }); console.log(numbers); for(var i=0; i 2) { throw new Error("there are more than 2 numbers missing in the sequence"); } else if(missing.length == 0) { missing.push(numbers[0]-1, numbers[0]-2); } return missing; }

Find my complete discussion here http://www.capacode.com/array/find-2-missing-numbers-in-array/ If we use boolean of array to store numbers in A, then this problem is simple. It runs in O(N) and use O(N) memory. How to optimize memory here? First, we can easily find the sum of two missing numbers which is (N * (N + 1) / 2 ) – Sum(A). For example, given the problem, sum of two missing numbers is 5. We need another information to find two missing numbers. We can similar compute the product of two numbers which is N! / Product(A). After having sum and product of two numbers, we can easily find those numbers. However, the problem is N! can be large and overflow. We can similar find the xor of two missing numbers. Just Xor all number in A with all numbers from 1 to N. However, Xor and Sum operator are quite similar and they can not find to which number missing. Next is the best efficient solution as I know. We know sum of two numbers, for example, in this case is 5. Thus, one number must be less than or equal 2 and one number must be greater than or equal 3. So, next we just compute sum of all number less than or equal 2, and sum of all number greater than or equal 3. Finally we can find two missing number. Specifically, first sum is 1, second sum is 4 + 5 = 9. However, in complete array, first sum should be 1 + 2 = 3, second sum should be 3 + 4 + 5 = 12. Thus two missing number is 2 and 3 :)