EasyStackDesignQueue

Implement Queue using Stacks

LeetCode
1 approach, code in all languages

Build a first-in-first-out (FIFO) queue whose entire internal storage is limited to standard stacks. A stack only exposes the usual last-in-first-out operations: push a value on top, pop the top value, look at the top value, and check whether it is empty.

Implement the class MyQueue with the following methods: push(x) adds element x to the back of the queue, pop() removes and returns the element at the front, peek() returns the front element without removing it, and empty() reports whether the queue currently holds no elements.

Your implementation may use one or more stacks, but you are not allowed to reach into the middle of any stack. Every access must go through the top of a stack.

Example 1

Input: operations = ["MyQueue", "push", "push", "peek", "pop", "empty"] args = [[], [1], [2], [], [], []]

Output: [null, null, null, 1, 1, false]

After pushing 1 then 2, peek returns the front element 1. pop removes and returns 1. The queue still holds 2, so empty is false.

Example 2

Input: operations = ["MyQueue", "push", "pop", "empty"] args = [[], [7], [], []]

Output: [null, null, 7, true]

A single element 7 is pushed and immediately popped, leaving the queue empty.

Constraints

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All calls to pop and peek are valid: they are only made on a non-empty queue.
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