Given the following problem, I will be grateful for any corrections, since I do not have a solution for the current question (taken from one of my exams professors !!!):
Note: this is not homework!
Problem:
For two sorted arrays A (with length n ) and B (with length m ), where each
Element
(in both arrays) is a real number, and the number X (also a real number),
we would like to know whether a ∈ A and b ∈ B exist or not, for example:
a + b = X , at O(n+m) runtime.
Decision:
First, we start checking from the end of both arrays, since we do not need numbers that are larger than X :
Define j = 0. Now start with the current i in A and from j to B :
while i > 0 , j < k :if A[i]+B[j] == X , then return both cells- else
j = j+1 , i = i -1
As a result, we will either have two elements, or we will go beyond the bounds of one or both arrays, which means that there are no two elements, such a + b = X
Any comments would be greatly appreciated
thanks
source share