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.
This was easy. Some tips.
You can move all the elements from one stack to the other every insert/push but this won't be very efficient.
So, instead, just keep an stack of all the elements as they come. When a peek/pop operation comes, move your elements from the first stack to the second. (Step 0) After this comes the interesting part.
For any subsequent inserts/push, keep pushing to your first stack.
For subsequent peek/pop operation just take elements from the second stack.
If the second stack becomes empty from pop operations, then repeat Step 0.
Javascript ES6 version follows:
classQueue{constructor(){this.firstStack=[];this.secondStack=[];}enqueue(value){this.firstStack.push(value);}dequeue(value){this.prepareStacks();returnthis.secondStack.pop();}prepareStacks(){if(this.secondStack.length===0){while(this.firstStack.length>0){this.secondStack.push(this.firstStack.pop());}}}getHead(){// Assume we cannot read directly from index for more funthis.prepareStacks();varvalue=this.secondStack.pop();this.secondStack.push(value);returnvalue;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queues: A Tale of Two Stacks
You are viewing a single comment's thread. Return to all comments →
This was easy. Some tips. You can move all the elements from one stack to the other every insert/push but this won't be very efficient.
So, instead, just keep an stack of all the elements as they come. When a peek/pop operation comes, move your elements from the first stack to the second. (Step 0) After this comes the interesting part.
Javascript ES6 version follows: