Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example 1:
Input:
nums = [3,0,1]
Output:
2
Explanation:
n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
In this approach, we will iterate over the nums array and check whether the loop index exists in the nums array. It will return that index as a missing number if it doesn’t exist.
function missingNumbers(nums){
for(let i=0;i<=nums.length;i++){
if(!nums.includes(i)){
return i;
}
}
}
let nums = [3,0,1];
let missingNumber = missingNumbers(nums);
console.log(missingNumber);
let nums = [0,3,1,4,2]; const n = nums.length; const Tsum = (n*(n+1)) /2; const actualSum = nums.reduce((acc,num) => acc + num,0); console.log(Tsum-actualSum);