Could you please help me with this one? :
“Let A and B are an incrementally ordered arrays of natural numbers and K be some arbitrary natural number. Find an effective algorithm which determines all possible pairs of indexes (i,j) such that A[i]+B[j]=K. Prove algorithm’s correctness and estimate its complexity.”
Should I just iterate over the first array and do a binary search on the other one?
Thanks 🙂
No!
Both arrays are ordered, so you do the following:
itAon the beginning ofAitBon the end ofB*itA + *itBat each iteration. If the value is equal toK, return both indexes. If the value is smaller thanK, incrementitA. Else, decrementitB.When you go through both arrays, you are done, in linear time.