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,
If the arrays are sorted you can do it in linear time and constant storage.
If the arrays are initially unsorted then you can first sort them then use the above algorithm. There a few different approaches for sorting them that you could use, depending on the type of data you expect:
A comparison sort will require O(n log n) time on average. The last two are faster than O(n log(n)) but can be impractical if the range of possible values in the input arrays is very large.