RECURSION & BACKTRACKING › RECURSION PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The input describes the stack from bottom to top, but the output describes what repeated popping produces. After sorting, the smallest value must be at the bottom and the largest value must be at the top. Popping therefore removes values from largest to smallest, so the returned array must be in non-increasing order.
That means the stack operation does not require a special recursive rearrangement here. The array already contains the complete stack, and sorting it in descending order directly creates the required top-to-bottom representation. Sorting keeps equal values as separate occurrences, so duplicates need no special handling.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n log n) | std::sort performs comparison sorting over all n elements; its worst-case implementation guarantee keeps the number of comparisons within O(n log n), and each comparison takes constant time for integers. |
| Space | O(log n) extra | The returned array is required output and is excluded from the working-space bound. The array itself is rearranged in place, while std::sort uses recursion or equivalent bookkeeping whose stack space is O(log n); this remains logarithmic even for an already sorted or highly ordered input. |
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> sortStack(vector<int> st) {
sort(st.begin(), st.end(), greater<int>());
return st;
}
};The comparator is the key line: the default sort order would place the smallest value first, which represents the bottom of the sorted stack rather than its first popped value. greater<int>() places the largest value first, so index 0 of the returned array represents the top element and each later index represents the next pop.