Finding special kind of elements with in an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in three arguments, namely −

arr --> an array of integers
m --> a positive integer
n --> a positive integer

The task of our function is to find out whether there exists two such elements (lets call them a1 and a2) such that −

  • The absolute difference between a1 and a2 is at most m

  • The absolute difference between the indices of a1 and a2 is at most n

Example

Following is the code −

const arr = [1, 2, 3, 1, 7, 8];
const findSpecialElements = (arr = [], m, n) => {
   const map = arr
   .map((el, ind) => ({ el, ind }))
   .sort((a, b) => a.el - b.el);
   let left = 0;
   let right = 1;
   while (right < map.length) {
      const diff = Math.abs(map[right].el - map[left].el);
      const range = Math.abs(map[right].ind - map[left].ind);
      if (diff <= n && range <= m){
         return true
      }else if (diff > n){
         left++;
      }else if (range > m){
         right++;
      };
      if (left === right){
         right++;
      };
   };
   return false;
};
console.log(findSpecialElements(arr, 3, 0));

Output

Following is the console output −

true
raja
Published on 18-Jan-2021 04:56:44
Advertisements