In addition to "small-sized vectors" and "no duplicates", if it is the case that your keys are always within a known, memory-supported range (e.g. "no key will ever be greater than 10.000"), then you can leverage this extra info to achieve an O(max(N,M)) (linear time!) solution ( @Jarod's is O(max(N,M) * log(N+M)) and @Adrian's is O(N*M)).
First, establish a large enough prime (i.e. a prime larger than the largest key) and then start to build a hashmap up to the point where the first collision happens.
std::pair<size_t, size_t> findFirstMatch(const std::vector<int>& u, const std::vector<int>& v, const int& prime) {
std::vector<size_t> hashmap(prime, INT_MAX); // ---> 'INT_MAX' returned if no common entries found.
size_t smallerSz = std::min(u.size(), v.size());
std::pair<size_t, size_t> solution = { INT_MAX, INT_MAX };
bool noCollision = true;
// Alternate checking, to ensure minimal testing:
for (size_t i = 0; i < smallerSz; ++i) {
//One step for vetor u:
size_t& idx = hashmap[u[i] % prime];
if (idx < INT_MAX) { // ---> Collision!
solution = { i, idx };
noCollision = false;
break;
}
idx = i;
//One step for vector v:
idx = hashmap[v[i] % prime];
if (idx < INT_MAX) { // ---> Collision!
solution = { idx, i };
noCollision = false;
break;
}
idx = i;
}
//If no collisions so far, then the remainder of the larger vector must still be checked:
if(noCollision){
const bool uLarger = u.size() > v.size();
const std::vector<int>& largerVec = (uLarger) ? u : v;
for (size_t i = smallerSz; i < largerVec.size(); ++i) {
size_t& idx = hashmap[largerVec[i] % prime];
if (idx < INT_MAX) { // ---> Collision!
if (uLarger) solution = { i, idx };
else solution = { idx, i };
break;
}
idx = i;
}
}
return solution;
}
USAGE
int main()
{
std::vector<int> u = { 32, 25, 13, 42, 55, 33 }, v = { 18, 72, 53, 39, 13, 12, 28 };
const int prime = 211; // ---> Some suitable prime...
std::pair<size_t, size_t> S = findFirstMatch(u, v, prime);
std::cout << "Solution = {" << S.first << "," << S.second << "}.";
return 0;
}
It outputs "{2, 4}" instead of "{3, 5}" because the first index is 0. Feel free to modify it.