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
- if calculated average pair bigger than the expected value
- 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;
}
Top comments (0)