
Problems
Step 1:Push the element into the Q2.Step 2:Push the remaining elements of Q1 into Q2.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();
*/Q1: Two Stacks
Q1: Two StacksQ2: Reverse a string using a Stack
Q2: Reverse a string using a StackNot 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)
Q8: Sort a Stack
Q8: Sort a StackTime Complexity: O(n)
Space Complexity: O(n) // because of stack
Q10: Check palindrome
Q10: Check palindromeQ13: Count of Smaller Numbers After Self --> pending
Q13: Count of Smaller Numbers After Self --> pendingQ14: Next Smaller Element
Q14: Next Smaller Element Q15: Previous Smaller Element
Q15: Previous Smaller ElementQ16: Min Index
Q16: Min IndexQ17: Search in Stack and restore it in the same position.
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)
Q18: 2 Sorted Stack (min on top) inserted into 3rd Stack (min on top)Q19: Remove All Duplicates
Q19: Remove All DuplicatesLast updated
Was this helpful?