Special arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

An array is said to be a special array if there exists a positive integer num, such that there are num elements greater than num in the array. The number num does not necessarily have to belong to the array, it should just exist.

For example − If the input array is −

const arr = [2, 1, 5, 2, 7, 9];

Then, if we examine properly, we will find that for num = 3, there are exactly 3 elements greater than 3 in this array.

However, 3 is not a part of this array, but that's valid. Therefore, we are required to write a JavaScript function that takes in an array of Numbers.

The function should return the number around which it is special, (if it is special at all), otherwise the function should return -1.

Example

const arr = [2, 1, 5, 2, 7, 9];
const findSpecialArray = (array = []) => {
   const arr = array.slice().sort((a, b) => a - b);
   let index = 1;
   const { length } = arr;
   while(index <= arr[length-1]){
      let num = 0;
      for(let i=0; i<length; i++){
         if(arr[i] >= index){
            num++;
         }
      };
      if(num === index){ return index; };
      index++;
   };
   return -1;
};
console.log(findSpecialArray(arr));

Output

This will produce the following output −

3
raja
Published on 25-Nov-2020 05:19:16
Advertisements