1. Array Transfer & Standard Sort
Intuition
Empty the stack into an array or list. Sort the list in ascending order using standard library sort O(N log N). Then push all elements from index 0 to N-1 back into the stack so that the maximum element rests at the top.
When to apply: Baseline comparison when loop/auxiliary storage constraints are not enforced.
Algorithm
- Pop all elements from stack into a dynamic array
arr. - Sort
arrin ascending order. - Push sorted items back into stack in order.
#include <iostream>#include <stack>#include <vector>#include <algorithm> using namespace std; class Solution {public: void sortStackArray(stack<int>& s) { vector<int> arr; while (!s.empty()) { arr.push_back(s.top()); s.pop(); } sort(arr.begin(), arr.end()); for (int v : arr) { s.push(v); } }}; int main() { stack<int> s; s.push(11); s.push(2); s.push(32); s.push(3); s.push(41); Solution sol; sol.sortStackArray(s); while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Draining takes O(N), standard sort takes O(N log N), and reloading takes O(N). - Space complexity:
O(N)— Auxiliary array stores all N elements.