Implement Stack using Queues

EasyStackdesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Build a last-in-first-out stack, MyStack, whose internal storage is made of **queues only**. A queue may only add to the back, remove from the front, look at the front, report its size and report whether it is empty (for example collections.deque restricted to append, popleft, [0] and len). Implement: - MyStack() creates an empty stack. - push(x) places x on top of the stack. - pop() removes and returns the top element. - top() returns the top element without removing it. - empty() returns true if the stack is empty, otherwise false. pop and top are only called on a non-empty stack. A single queue is enough; O(n) push with O(1) pop/top is the expected trade-off.

Examples

Input: ["MyStack","push","push","top","pop","empty"] [[],[4],[9],[],[],[]]
Output: [null,null,null,9,9,false]
The last value pushed, 9, is on top, so `top` and `pop` return 9. The 4 is still there, so `empty` is false.
Input: ["MyStack","push","pop","push","push","pop","top","pop","empty"] [[],[1],[],[2],[3],[],[],[],[]]
Output: [null,null,1,null,null,3,2,2,true]
After 1 is popped, 2 and 3 are pushed. `pop` returns 3, leaving 2 on top, and popping 2 empties the stack.

Constraints

  • 1 <= x <= 100
  • At most 1000 calls are made in total.
  • `pop` and `top` are never called on an empty stack.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems