Given a sorted array and a number x, find a pair in that array whose sum is closest to x". How can we implement this with O(n) time complexity?
Example:
fn([10,22,28,29,30,40], 54) // => [22, 30]
fn([1,3,4,7,10], 15) // => [4, 10]
fn([5], 7) // => []
fn([], 7) // => []
Update:
It was my latest try to solve this problem, which isn't working and it has O(n^2) time complexity.
function fn(arr, x) {
let res = [];
if (arr.length < 2) return res;
for (let i = 0; i < arr.length - 1; i++) {
for (let j = arr.length - 1; j > i; j--) {
let t = Math.abs(arr[i] + arr[j] - x);
if (arr[i] + arr[j] === x) return (res = [arr[i], arr[j]]);
if (arr[i] + arr[j] > x) {
if (t > Math.abs(arr[i] + arr[j] - x)) {
t = Math.abs(arr[i] + arr[j] - x);
res = [arr[i], arr[j]];
}
}
}
}
return res;
}
console.log(fn([10, 22, 28, 29, 30, 40], 54));
console.log(fn([1, 3, 4, 7, 10], 15));