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



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
Updated on: 2020-11-21T09:30:50+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements