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,
I used C++ and it seemed to give me the desired result. Hope this is what you were looking for.
using namespace std;
using data=std::pair;
void search_pairs(std::vector& A, std::vector& B, const int total, std::vector& output){
std::sort(A.begin(),A.end(),[](const int i,const int j)->bool{return (ibool{return (a* minV(nullptr);
std::vector* maxV(nullptr);
if(A.size()>B.size()) {minV=&B;maxV=&A;}
else {minV=&A;maxV=&B;}
for(auto&& itr:(*minV) ){
auto remain(total-itr);
if (std::binary_search (maxV->begin(), maxV->end(), remain)){
data d{itr,remain};
if (minV==&B) std::swap(d.first,d.second);
output.push_back(d);
}
}
if (minV==&B) std::reverse(output.begin(),output.end());
}
int main() {
size_t nb(0);
scanf("%lu",&nb);
for (size_t i=0;i A,B;
for (size_t i=0;i output;
search_pairs(A, B, total, output);
auto itr=std::begin(output);
if (itr==std::end(output)) printf("-1");
while (itr!=std::end(output)){
printf("%d %d",(*itr).first, (*itr).second);
if (++itr!=std::end(output)) printf(", ");
}
printf("\n");
}
//code
return 0;
}