Page cover

Problems

654B
Open

  1. Step 1: Push the element into the Q2.

  2. Step 2: Push the remaining elements of Q1 into Q2.

  3. Step 3: Swap(Q1, Q2).

class MyStack {
    queue<int> q1, q2;
public:
    
    void push(int x) {
        q2.push(x);

        while(!q1.empty()) {
            q2.push(q1.front());
            q1.pop();
        }
        
        swap(q1, q2);
    }
    
    int pop() {
        if(q1.empty())return -1;

        int d = q1.front();
        q1.pop();
        return d;
    }
    
    int top() {
        return q1.front();
    }
    
    bool empty() {
        return q1.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

Q2: Reverse a string using a Stack

Not a Good approach because the time and space complexity of this program is O(n)

Best Approach: Reverse a string using STL Build-in Function reverse()

Function
Time Complexity
Space Complexity

insertatBottom()

O(n)

O(n)

reverseStack()

O(n)

O(n)

  • Time Complexity: O(n)

  • Space Complexity: O(n) // because of stack

Q10: Check palindrome

Q15: Previous Smaller Element

Q16: Min Index

Q17: Search in Stack and restore it in the same position.

Q18: 2 Sorted Stack (min on top) inserted into 3rd Stack (min on top)

Q19: Remove All Duplicates

Last updated

Was this helpful?