DEV Community

Dumb Down Demistifying Dev
Dumb Down Demistifying Dev

Posted on

3 3

Find The Average Pair

Multi-Pointers QUestion 2

Given a sorted array and a target average value, write a function AveragePair to determine if a pair of numbers adds up to the target average value.

Thoughts:

  • One pointer at the start of the array
  • One pointer at the end of the array
  • Since the array is sorted,
    • if calculated average pair bigger than the expected value
      • we move left pointer by 1 position to the right
    • if calculated average pair smaller than the expected value
      • we move right pointer by 1 position to the left
  • Practice both iterative and recursive methods
// Recursive method
function averagePair(sortedArr, avgNum){
    const arrLength = sortedArr.length;
    if (arrLength < 1) return false;

    function recurs(sortedArr, left, right) {
        if (left === right) return false;

        const avg = (sortedArr[left] + sortedArr[right]) / 2;
        if (avg === avgNum) return true;
        return (avg < avgNum) 
            ? recurs(sortedArr, left+=1, right)
            : recurs(sortedArr, left, right-=1);
    }

    return recurs(sortedArr, 0, arrLength - 1);
}

// Iterative method
function AveragePair(sortedArr, avgNum){
    const arrLength = sortedArr.length;
    if (arrLength < 1) return false;

    let left = 0;
    let right = arrLength - 1;
    while(right > left) {
        const avg = (sortedArr[left] + sortedArr[right]) / 2;
        if (avg === avgNum) return true;
        if (avg < avgNum) {
            left++;
        } else {
            right--;
        }
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay