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.
function equalStacks(h1, h2, h3) {
// util method to get the sizes
const sum = (h) => h.reduce((acc, curr)=> acc + curr, 0);
// instantiate the stack sizes first, and cache for performance
const stackSizes = new Map();
stackSizes.set(h1, sum(h1));
stackSizes.set(h2, sum(h2));
stackSizes.set(h3, sum(h3));
// check everytime if we have equal stack now
const allEqual = () => stackSizes.get(h1) === stackSizes.get(h2) && stackSizes.get(h2) === stackSizes.get(h3);
while(!allEqual()) {
// find heighest from which we remove per loop
let highest = h1;
if(stackSizes.get(h2) > stackSizes.get(highest)) {
highest = h2;
}
if(stackSizes.get(h3) > stackSizes.get(highest)) {
highest = h3;
}
// update the size cached
// and remove one from the highest
stackSizes.set(highest, stackSizes.get(highest) - highest.shift());
// and continue check again if equal in the next loop
}
// any one of them should be okay now
// return the height (sum) of the stack
return stackSizes.get(h1);
}
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 →
JS
}