← Home

232. Implement Queue using Stacks

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
data structure designC++Markdown
232

The trick here is to name the state correctly, then let the implementation follow. For 232. Implement Queue using Stacks, the solution in this repository is mainly a data structure design solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: data structure design, stack.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are push, pop, peek, empty.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Implement Queue using Stacks.
02//Memory Usage: 8.8 MB, less than 97.79% of C++ online submissions for Implement Queue using Stacks.
03
04/**
05push:  O(n), O(n)
06pop:   O(1), O(1)
07peek:  O(1), O(1)
08empty: O(1), O(1)
09**/
10
11class MyQueue {
12public:
13    stack<int> stk;
14    
15    /** Initialize your data structure here. */
16    MyQueue() {
17    }
18    
19    /** Push element x to the back of queue. */
20    void push(int x) {
21        stack<int> tmp;
22        while(!stk.empty()){
23            tmp.push(stk.top());
24            stk.pop();
25        }
26        stk.push(x);
27        while(!tmp.empty()){
28            stk.push(tmp.top());
29            tmp.pop();
30        }
31    }
32    
33    /** Removes the element from in front of queue and returns that element. */
34    int pop() {
35        int tmp = stk.top();
36        stk.pop();
37        return tmp;
38    }
39    
40    /** Get the front element. */
41    int peek() {
42        return stk.top();
43    }
44    
45    /** Returns whether the queue is empty. */
46    bool empty() {
47        return stk.empty();
48    }
49};
50
51/**
52 * Your MyQueue object will be instantiated and called as such:
53 * MyQueue* obj = new MyQueue();
54 * obj->push(x);
55 * int param_2 = obj->pop();
56 * int param_3 = obj->peek();
57 * bool param_4 = obj->empty();
58 */
59 
60 /**
61 Approach #2 (Two Stacks) Push - O(1)O(1) per operation, Pop - Amortized O(1)O(1) per operation.
62 **/
63 
64 /**
65push:  O(1), O(n)
66pop:   amortized O(1), worst O(n), O(1)
67peek:  O(1), O(1)
68empty: O(1), O(1)
69**/
70
71/**
72class MyQueue {
73public:
74    stack<int> s1, s2;
75    int front;
76    
77    /** Initialize your data structure here. */
78    MyQueue() {
79    }
80    
81    /** Push element x to the back of queue. */
82    void push(int x) {
83        if(s1.empty()) front = x;
84        s1.push(x);
85    }
86    
87    /** Removes the element from in front of queue and returns that element. */
88    int pop() {
89        if(s2.empty()){
90            while(!s1.empty()){
91                s2.push(s1.top());
92                s1.pop();
93            }
94        }
95        int tmp = s2.top();
96        s2.pop();
97        return tmp;
98    }
99    
100    /** Get the front element. */
101    int peek() {
102        if(!s2.empty()){
103            return s2.top();
104        }
105        return front;
106    }
107    
108    /** Returns whether the queue is empty. */
109    bool empty() {
110        return s1.empty() && s2.empty();
111    }
112};
113**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.