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).

Algorithm Approach

The two-pointer technique works efficiently on sorted arrays. We maintain pointers at both ends and move them based on whether the current average is greater or less than the target.

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));
console.log(averagePair(arr, 3));
console.log(averagePair(arr, 10));

Output

And the output in the console will be ?

true
true
false

How It Works

The algorithm uses the mathematical property that if the average of two numbers equals the target, then their sum equals 2 × target. For example, if we want average 6.5, we need pairs that sum to 13 (2 × 6.5).

The two pointers start at opposite ends. When the sum is too large, we move the right pointer left. When we find a matching sum, we return true.

Time and Space Complexity

This solution has O(n) time complexity since each element is visited at most once by either pointer, and O(1) space complexity as we only use two pointer variables.

Conclusion

The two-pointer technique efficiently finds pairs with a target average in sorted arrays. This approach leverages the sorted property to achieve optimal time and space complexity.

Updated on: 2026-03-15T23:19:00+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements