Reverse a Stack
Problem Statement:β
You are given a stackΒ St. You have to reverse the stack using recursion.
-
Example:
Example 1:
Input:
St = {3,2,1,7,6}
Output:
{6,7,1,2,3}
Explanation:
Input stack after reversing will look like the stack in the output.
Example 2:
Input:
St = {4,3,9,6}
Output:
{6,9,3,4}
Explanation:
Input stack after reversing will look like the stack in the output.
Solution:β
class Solution {
public:
// Helper to insert an element at the bottom of the stack
void InsertAtBottom(stack<int> &s, int x) {
if (s.empty()) {
s.push(x);
return;
}
int temp = s.top(); // Pop top element
s.pop();
InsertAtBottom(s, x); // Insert x at bottom recursively
s.push(temp); // Push the popped element back
}
// Main recursive function to reverse the stack
void Reverse(stack<int> &St) {
if (!St.empty()) {
int x = St.top();
St.pop();
Reverse(St); // Reverse the smaller stack
InsertAtBottom(St, x); // Insert removed element at bottom
}
}
};
β How It Worksβ
-
Two recursive functions are used:
Reverse()β pops all elements to the bottomInsertAtBottom()β puts each element back at the bottom, reversing the stack
-
Key idea:
Pop all elements one by one
and insert each at the bottom during backtracking
π§ Key Pointsβ
- The call stack itself stores the popped elements
InsertAtBottom()is a helper that places an element at the bottom of the stack recursively- Recursive base:
- For
Reverse: stop when stack is empty - For
InsertAtBottom: insert when stack becomes empty
- For
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(nΒ²) β |
| Space | O(n) recursion |
β οΈ Edge Casesβ
- Empty stack β no change
- Single element stack β remains same
- All elements same β order doesn't matter but works
π‘ Other Approachesβ
| Approach | Time | Space |
|---|---|---|
| Recursion β | O(nΒ²) | O(n) |
| Iterative (with extra stack) | O(n) | O(n) |
π Related Problemsβ
- Sort a Stack using Recursion
- Insert element at bottom of stack
- Design Stack with Min/Max
- Implement Stack using Queue
π¬