DSA Stacks

Implement Queue Using Stacks

Two stacks — push onto in-stack; pop/peek lazily transfer to out-stack to reverse order.

Easy
Time O(1) amortized Space O(n)
LeetCode
3 min read
stack queue design

Problem#

Implement a FIFO queue using only two LIFO stacks. Support push, pop, peek, and empty.

Examples#

  • push(1), push(2), peek() → 1, pop() → 1, empty() → false

Constraints#

  • 1 <= x <= 9 (problem-given). At most 100 calls to each method.

Approach#

Use in stack for pushes and out stack for pops. When out is empty and a pop or peek is requested, pour everything from in into out — that reverses the LIFO order into FIFO.

Solution#

Implement Queue Using Stacks
class MyQueue {
stack<int> in, out;
void shift() {
if (out.empty())
while (!in.empty()) { out.push(in.top()); in.pop(); }
}
public:
void push(int x) { in.push(x); }
int pop() {
shift();
int v = out.top(); out.pop();
return v;
}
int peek() {
shift();
return out.top();
}
bool empty() { return in.empty() && out.empty(); }
};

Editorial#

Each element moves between stacks at most twice (push, transfer), making the amortized cost per operation O(1). Lazy transfer is critical — eagerly moving on every push would degrade pop to O(n).

Complexity#

  • Time: O(1) amortized per operation.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.