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.
Oh man, if I had just thought about it a bit more, I maybe would have come up with this, but my version was so inefficient that I kept timing out.
What I did was, for each enque, I put all the values from the "front" stack to the "back" stack, pushed the new value to the "front" stack, then pulled all the values BACK from the "back" stack. Then I would just deque and peek from the front stack. O(2n) for every insert is BAD, man.
It also didn't help that early on I implemented my own stack (for fun) that was a recursive type, so I'm pretty sure some of the tests errored out from hitting the recursion limit.
Your solution saved me.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
Oh man, if I had just thought about it a bit more, I maybe would have come up with this, but my version was so inefficient that I kept timing out.
What I did was, for each enque, I put all the values from the "front" stack to the "back" stack, pushed the new value to the "front" stack, then pulled all the values BACK from the "back" stack. Then I would just deque and peek from the front stack. O(2n) for every insert is BAD, man.
It also didn't help that early on I implemented my own stack (for fun) that was a recursive type, so I'm pretty sure some of the tests errored out from hitting the recursion limit.
Your solution saved me.