I have some problem in my homework, I’m given two arrays A,B (they are sorted) with n elements each one, I need to find (n*logn) minimal elements (or n if it is possible) from the array which cosists of elements which is sum of one element from array A and one element from array B, total number of elemnts in C will be n^2, – C = {a+b | a belongs to A, b belongs to B}, I need to make it with complexity O(n*logn).
Thanks in advance for any help!
P.S. I tried to solve it but I have some problems. I know that the first element will be a1 + b1, a1 first element from A, b1 first element from B.
edited
Also all elements in C are different.
I’m not giving you the answer, but here are a few hints to get you thinking in the right direction.
So let’s say you have. Keep in mind that these lists are already sorted, this is very important.
{a1,a2,a3}
{b1,b2,b3}
As you correctly said, the first element is a1+b1. Why? Because those are the smallest numbers in both arrays, so their sum will be the smallest.
Now what options do you have for the second element? Remember that the list is sorted!
Could it be a1+b2?
Could it be a1+b3?
And then for the opposite,
Could it be b1+a2?
Could it be b1+a3?
Could it be b2+a2?
(two yes answers and three no answers above)
Using this you should be able to figure out how you find the second smallest element and from here it should be easy to find how to do that for all elements.
If you are still confused, ask questions in the comments.
GL!