Consider an array of numbers from 1 to 100. In this array, duplicate elements are not allowed. Also, there is one number missing in this array. We will find that by following the steps provided below:
Step 1: Calculate the sum of numbers from 1 to 100 using the sum of natural numbers formula given below:
Step 2: Find the sum of the values present in the array.
Step 3: Subtract the sum of the elements of the array from the sum of 1 to 100 numbers. We'll get the missing number as a result.
function findMissedNum(arrayOfNumbers, n = 100) {if(arrayOfNumbers.length === n) {console.log("no number is missed");}if(arrayOfNumbers.length < (n - 1) ) {console.log("more than one number is missed")}let totalSum = (n * (n+1)) / 2;let sumOfArray = 0;for(let i of arrayOfNumbers){sumOfArray += i;}return totalSum - sumOfArray;}// create an array with values 0 to 100let arrayOfNumbers = Array.from( Array(101).keys())// remove the 0th elementarrayOfNumbers.shift();// now the array will 1 to 100// remove the value at index 50.(means remove 51 from the array)arrayOfNumbers.splice(50, 1)// now the array is 1 to 100 but without the number 51let missedNum = findMissedNum(arrayOfNumbers, 100);console.log("The missing number is :", missedNum)
findMissedNum
function that will find the missing number of an array using the above algorithm.arrayOfNumbers
.Array(101)
array returns an array with 101 empty elements. keys
method, which returns an array iterator object that contains the key of each index. In our case, iterator from is from 0 to 100. Array.from
method with the array iterator as an argument. This method returns a new array with the values of the array iterator. We get an array with values 0 to 100. shift
method to remove the first element of the array. Now the array will be 1 to 100.slice
method to remove the element at index 50. Element 51 will be removed from the array.findMissedNum
method. This method returns the missing number 51 as result.