I am looking for the solution of following algorithm with minimal time and space complexity.
Given two arrays a and b, find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k (any integer).
I was able to come up with O(n log n) approach where we will sort one of the array say A and for each of the element b in array B, do binary search on sorted array A for value (K-b) .
Can we improve it any further?
If you have a limit on the maximum possible number (let’s name it M) then you can have a solution in O(M+n).
Boolean array of false and mark as true all value for element of A. Then for each element b of B check if the element number K-b is marked as true.
You can improve it if you are using an hash-map instead of a big array. But I would not consider that in this kind of questions hash-map is kind of cheating.
Anyway it would give you O(n) for insertion and then O(n) for query, O(n) in total.
EDIT :
One case where this might be useful.
Using my idea not with boolean but integer (incremented at each run) gives you a complexity of :
You are using more space but you’ve increased speed by a factor log(n) ~=20 in this case !