Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest pair sum in two sorted arrays

Given two sorted arrays of integers, a and b, and an integer c, I have to find i,j such that:

a[i] + b[j] <= c

and a[i] + b[j] is large as possible.

The best solution I can think of is in O(nlogn) time, taking every integer from first array and finding the lower bound of "c-a[i]".
Can anyone suggest me a better way to do this (maybe in O(n) time)?

like image 537
akash Avatar asked Jun 27 '12 10:06

akash


People also ask

How do you find the closest pair of an array?

Traverse the array and for each i, do the following : Find the lower bound for x/arr[i] in the sub-array on the right of arr[i], i.e., in subarray arr[i+1..n-1]. Let it be denoted by l. Find the upper bound for x/arr[i] in the sub array on the right of arr[i], i.e., in sub array arr[i+1..n-1].

How do you find all pairs of elements in an array whose sum is equal to a given number?

Follow the steps below to solve the given problem: Initialize the count variable with 0 which stores the result. Iterate arr and if the sum of ith and jth [i + 1…..n – 1] element is equal to sum i.e. arr[i] + arr[j] == sum, then increment the count variable. Return the count.


2 Answers

Thinking a bit about it, then you could ask yourself:
"Is it necessary, each time, to search in the sorted b-array for successive values from a[]?"

like image 83
jeb Avatar answered Sep 30 '22 08:09

jeb


I think you dont have to search the whole array b[] next time.......u have to search in between starting of array b and the lowest bound u found till now....for the next element in a[].It would definitely reduce your time complexity...and when u find the given target 'c' you must stop your search.

like image 45
sumit Avatar answered Sep 30 '22 06:09

sumit