EasyStackDesignQueue

Implement Stack using Queues

LeetCode
1 approach, code in all languages

Build a last-in-first-out (LIFO) stack whose entire internal storage is limited to standard queues. A queue only exposes first-in-first-out operations: enqueue a value at the back, dequeue the value at the front, peek at the front value, and check whether it is empty.

Implement the class MyStack with the following methods: push(x) adds element x to the top of the stack, pop() removes and returns the element on top, top() returns the top element without removing it, and empty() reports whether the stack currently holds no elements.

You may use one or more queues, but you may only interact with them through their standard queue operations.

Example 1

Input: operations = ["MyStack", "push", "push", "top", "pop", "empty"] args = [[], [1], [2], [], [], []]

Output: [null, null, null, 2, 2, false]

After pushing 1 then 2, the top is 2. pop removes and returns 2, leaving 1 in the stack so empty is false.

Example 2

Input: operations = ["MyStack", "push", "pop", "empty"] args = [[], [5], [], []]

Output: [null, null, 5, true]

A single element 5 is pushed then popped, so the stack ends up empty.

Constraints

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, top, and empty.
  • All calls to pop and top are valid: they are only made on a non-empty stack.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now