We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
int equalStacks(vector h1, vector h2, vector h3) {
//reverse each vector and find the cumulative sum
reverse(h1.begin(),h1.end());
for(int i = 1; i < h1.size(); i++){
h1[i] = h1[i] + h1[i-1];
}
reverse(h2.begin(),h2.end());
for(int i = 1; i < h2.size(); i++){
h2[i] = h2[i] + h2[i-1];
}
reverse(h3.begin(),h3.end());
for(int i = 1; i < h3.size(); i++){
h3[i] = h3[i] + h3[i-1];
}
/*create copies and copy the vectors such that 'search' will be the vector with shortest length and 'cp1' & 'cp2' being the other two */
vector<int> search, cp1,cp2;
if(h1.size()<h2.size()) {
if(h1.size() < h3.size()) {
search = h1;
cp1 = h2;
cp2 = h3;
} else {
search = h3;
cp1 = h1;
cp2 = h2;
}
} else if(h2.size() < h3.size()){
search = h2;
cp1 = h1;
cp2 = h3;
} else {
search = h3;
cp1 = h1;
cp2 = h2;
}
//create a reverse iterator to start comparing values
vector<int>::reverse_iterator rit;
rit = search.rbegin();
int ans = 0;
/*for each value of starting from the end of 'search' vector, find if any of it exists in both 'cp1' and 'cp2'*/
while(rit != search.rend()) {
vector<int>::iterator it1,it2;
it1 = find (cp1.begin(), cp1.end(), *rit);
it2 = find (cp2.begin(), cp2.end(), *rit);
if(it1 != cp1.end() && it2 != cp2.end()){
ans = *rit;
break;
}
rit++;
}
return ans;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
A crude implementation of this approach:
}