Basically we need to return duplicated item and the missing item in array .
since the numbers are from 1 to n
their total sum will be n*(n+1)/2 (š mathematics)
Approach is simple just use a for loop and push each item in a new array only if its not in the new array , if its already present in new array then i don't push it instead store the duplicated item in a variable
i named the new array as - arrUnique
storing duplicated item in variable dup
the rest is understandable from code just have a look and try to understand
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function(nums) {
const arrUnique = [] ;
let dup = 0;
let remainingSum = 0;
const n = nums.length;
nums.forEach((num)=>{
if(arrUnique.includes(num)){
dup = num
}else{
remainingSum+=num;
arrUnique.push(num)
}
})
const sum = (n * (n+1)) / 2
return [dup,(sum-remainingSum) ]
};
Top comments (0)