Sort a Stack using recursion
Problem Statement:ā
Given a stack, the task is to sort it such that the top of the stack has the greatest element.
-
Example:
Example 1:
Input:
Stack: 3 2 1
Output: 3 2 1
Example 2:
Input:
Stack: 11 2 32 3 41
Output: 41 32 11 3 2
Solution:ā
// Helper function to insert an element x into a sorted stack
void sortedStack(stack<int> &s, int x) {
// Base: insert if stack is empty or x is larger than top
if (s.empty() || x > s.top()) {
s.push(x);
return;
}
// Pop top element to place x correctly
int temp = s.top();
s.pop();
sortedStack(s, x); // Recursive call to insert x in correct place
s.push(temp); // Push back the popped element
}
// Main recursive sort function
void SortedStack::sort() {
if (!s.empty()) {
int x = s.top(); // Remove top
s.pop();
sort(); // Sort remaining stack recursively
sortedStack(s, x); // Insert popped element at correct place
}
}
ā How It Worksā
- Use two recursive functions:
sort()ā removes all elements recursivelysortedStack(s, x)ā inserts each popped element back in sorted order
- Idea:
- Pop all elements ā sort smaller stack recursively
- Insert each popped element back at correct position using recursion
š§ Key Pointsā
- Works by simulating insertion sort logic using function call stack
sortedStack()placesxat correct position by popping larger elements- No need for any extra stack or array
- Base condition:
sortedStack(): insert if stack is empty orx > s.top()sort(): stop if stack is empty
ā±ļø Time & Space Complexityā
| Metric | Value |
|---|---|
| Time | O(n²) |
| Space | O(n) (recursion stack) |
ā ļø Edge Casesā
- Empty stack ā no operation needed
- Stack already sorted ā function still works correctly
- All identical elements ā no unnecessary swaps
š” Other Approachesā
| Approach | Time | Space |
|---|---|---|
| Recursion Only ā | O(n²) | O(n) |
| Use temp stack (iterative) | O(n log n) or O(n²) | O(n) |
š Related Problemsā
- Insert element in sorted stack
- Reverse a stack using recursion
- Sort queue using recursion
š¬