Given the following problem , I'd appreciate for any corrections since I have no solution for the current question (taken from one of my professor's exams !!!) :
Remark: this is no homework !
Problem:
Given two sorted arrays A
(with length n
) & B
(with length m
) , where each
element (in both arrays) is a real number , and a number X
(also a real number) ,
we'd like to know whether or not exists a ∈ A
and b ∈ B
, such as :
a + b = X
, in O(n+m)
running time .
Solution :
First , we start to check from the end of both arrays , since we don't need the numbers that are bigger than X
:
- i = n
k = m
while A[i] > X , i = i -1
- while B[k] > X , k = k -1
Define j = 0 .
Now start running from the current i
in A
, and from j
in B
:
while i > 0 , j < k
:if A[i]+B[j] == X
, then return both cells- else
j = j+1 , i = i -1
In the end we'd have either the two elements , or we'd reach out of bounds in one
or both of the arrays , which means that no two elements such a + b = X
are indeed exist .
Any remarks would be much appreciated
Thanks