I was asked to find the missing number from 1..N
array.
For instance, for array: let numArr = [2,4,6,8,3,5,1,9,10];
the missing number is 7
let numArr=[2,4,6,8,3,5,1,9,10];
numArr.sort(function(a,b){ //sort numArr
return a-b;
});
let newNumArr=[];
for(let i=1;i<=10;i++){
newNumArr.push(i);
}
for(let i=0;i<newNumArr.length;i++){ //pare with new arr
if(newNumArr[i] !== numArr[i]){
console.log('The missing num is:'+newNumArr[i]); //The missing num is:7
break;
}
}
I was asked to find the missing number from 1..N
array.
For instance, for array: let numArr = [2,4,6,8,3,5,1,9,10];
the missing number is 7
let numArr=[2,4,6,8,3,5,1,9,10];
numArr.sort(function(a,b){ //sort numArr
return a-b;
});
let newNumArr=[];
for(let i=1;i<=10;i++){
newNumArr.push(i);
}
for(let i=0;i<newNumArr.length;i++){ //pare with new arr
if(newNumArr[i] !== numArr[i]){
console.log('The missing num is:'+newNumArr[i]); //The missing num is:7
break;
}
}
Share
Improve this question
edited May 10, 2018 at 11:36
Mihai Alexandru-Ionut
48.5k14 gold badges105 silver badges132 bronze badges
asked May 10, 2018 at 9:08
DangurDangur
1391 silver badge7 bronze badges
1
- 2 Question best suited for codereview. Moreover from what question you are asking, it is not clear that 7 is the missing number unless and until you say so. Try rewording it to fit the code you have written – Krishna Prashatt Commented May 10, 2018 at 9:09
4 Answers
Reset to default 6You can use MAP
and FILTER
to find out the missing number in seperate array
const numArr = [2, 4, 6, 8, 3, 5, 1, 9, 10];
const missingNumberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(number => {
if (!numArr.includes(number)) {
return number;
}
}).filter(y => y !== undefined);
You can use the simple logic of sum of consecutive n
numbers is n*(n+1)/2
. Subtracting the sum of array numbers from above will give the missing number
let numArr=[2,4,6,8,3,5,1,9,10];
var sum = numArr.reduce((a,c) => a+c, 0);
// As the array contains n-1 numbers, here n will be numArr.length + 1
console.log(((numArr.length + 1) * (numArr.length + 2))/2 - sum);
It would be easier to use .find
:
function findMissing(input) {
input.sort((a, b) => a - b);
const first = input[0];
return input.find((num, i) => first + i !== num) - 1;
}
console.log(findMissing([2, 4, 6, 8, 3, 5, 1, 9, 10]));
console.log(findMissing([3, 4, 5, 6, 8, 9, 2]));
(note that this also works for finding missing values from arrays that don't start at 1)
You can use XOR
features.
XOR
all the array elements, let the result of XOR bearr_xor
.XOR
all numbers from 1 to n, let XOR beinterval_xor
.XOR
ofarr_xor
andinterval_xor
gives the missing number.
let numArr=[2,4,6,8,3,5,1,9,10];
function getMissingNo(arr){
arr = arr.sort()
n = arr.length
arr_xor = arr[0]
interval_xor = 1
for(i = 0; i < n; i++)
arr_xor ^= arr[i]
for( i = 0; i<n + 2; i++)
interval_xor ^= i
return arr_xor ^ interval_xor
}
console.log(getMissingNo(numArr));