Skip to content

Practice Implement Queue using Stacks

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#232
LeetCode Problem

Implement Queue using Stacks

Problem Statement

Build MyQueue as a FIFO queue using two stacks and only stack operations. push(x) appends at the back, pop() removes and returns the front, peek() reads the front without removal, and empty() reports whether there are no entries. pop and peek are called only when valid. Practice approach: Push into an input stack. For pop or peek, transfer all entries to an output stack only when that output stack is empty. The reversal exposes the oldest item. Each entry transfers at most once, giving amortized O(1) operations and O(n) space. Moving entries on every call would lose that bound.

Source: Implement Queue using Stacks on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["MyQueue","push","push","peek","pop","push","pop","pop","empty"]
[[],[4],[7],[],[],[2],[],[],[]]
Output
[null,null,null,4,4,null,7,2,true]
Explanation

The queue returns insertion order 4, 7, 2, even though 2 arrives after the first removal.

Constraints

1 <= x <= 9
At most 100 total calls to push, pop, peek, and empty.
Calls to pop and peek are valid.

Related LeetCode Problems

Practice more problems similar to Implement Queue using Stacks.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.