Find the Missing Number In JavaScript.
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.
First Approach.
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);
Second Approach.
- The sum of all elements in the range[0,n].
- A sum of nums.
- If we subtract both we will get the missing number.
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);