Finding the nth missing number from an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a strictly increasing sequence of number (increasing by a unit) in which some elements are missing like this −

const arr = [2,3,4,7,11];

We are required to write a JavaScript function that takes in one such array as the first argument and a single number, say n, as the second argument.

The function should find the nth element that missing from the array.

For example −

If for the above array, n = 4;

Then the output should be 8, because

The missing elements are −

1, 5, 6, 8

Example

const arr = [2, 3, 4, 7, 11];
const findMissing = (arr = [], n) => {
   let el = 0;
   let diff = 0;
   for(let i=0; i<arr.length; ++i) {
      const difference = arr[i] - el - 1;
      const sum = diff + difference;
      if(sum>=n) {
         break;
      };
      diff = sum;
      el = arr[i];
   }
   return el + n - diff;
};
console.log(findMissing(arr, 4));

Output

This will produce the following output −

8
raja
Published on 25-Nov-2020 05:35:15
Advertisements