Determine whether there is a pair of values in the array where the average of the pair equals to the target average in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of sorted integers and a target average as first and second arguments.

The function should determine whether there is a pair of values in the array where the average of the pair equals to the target average.

There's a solution with O(1) additional space complexity and O(n) time complexity. Since an array is sorted, it makes sense to have two indices: one going from begin to end (say y), another from end to begin of an array (say x).

Example

The code for this will be −

const arr = [1, 2, 4, 6, 7, 9, 11];
const averagePair = (arr = [], target = 1) => {
   let x = arr.length − 1;
   for (let y = 0; y < x; y++) {
      while (y < x && arr[x] + arr[y] > 2*target) {
         x−−;
      };
      if (x !== y && arr[x] + arr[y] === 2 * target) {
         return true;
      };
   };
   return false;
};
console.log(averagePair(arr, 6.5));

Output

And the output in the console will be −

true
raja
Published on 21-Nov-2020 09:30:16
Advertisements