Sort a Stack
Sort a Stack is a GFG problem (Medium). You get a stack of integers and must reorder it in place so the smallest value is at the bottom and the largest is on top.
- You may only push, pop, look at the top and check for empty.
- The intended answer uses no array and no built-in sort; recursion does the storing.
The stack holds up to 1,000 values, so a quadratic method is fast enough.
- 1 <= st.size() <= 10³
- 1 <= st[i] <= 10³
Intuition
A stack only shows its top, so there is nowhere to park values while you rearrange them. The trick is to use the call stack as hidden storage: pop a value into a local variable, let a deeper call sort what is left, then put the value back where it belongs.
- Sorting: pop the top, sort the smaller stack, insert the popped value. An empty stack is already sorted.
- Inserting into a sorted stack: if the top is not bigger than
x, pushx. Otherwise pop the top, insertxlower down, then push the popped value back on.
It is insertion sort, with each waiting value held by a call frame instead of an array slot.
"Rearrange a stack using only push and pop" points to recursion, because every call frame can hold one popped value. Reverse a Stack and Delete the Middle of a Stack use the same pop, recurse, push-back shape.
Approach
Before reading on, write a function that pushes x into a stack that is already sorted, keeping it sorted, with no loop and no extra container. Once that works, sorting the whole stack takes three more lines.
Two ways to solve it
Pop every value into call frames, then insert each one back into the sorted stack below it.
- No extra container: the call frames do the holding.
- Best fit: the recursive answer the problem expects.
Move values one by one onto a helper stack kept with its smallest value on top, sending bigger values back to the input stack whenever they block.
- Iterative: no recursion depth at all.
- Finish: pour the helper stack back so the largest value ends on top.
Both take O(n²) time. Recursion is the answer the problem is asking for, because it needs no second container; the second stack is the iterative version to reach for when recursion depth is a worry. The steps, code and live demo follow the recursive method, and the second-stack code comes after the demo.
Peel the stack with recursion
If the stack is empty, return. Otherwise pop the top into a local variable and call sortStack on what is left. When that call returns, the rest of the stack is sorted, and the popped value is still waiting in this call's variable.
Hand the value to a second function
Call insert(st, top). Push and pop cannot reach the middle of a stack, so a second recursive function does the digging, popping values off until it finds the spot where top fits.
Push when the top is not bigger
In insert, if the stack is empty or its top is <= x, push x and stop. The stack is already sorted, so everything below the top is smaller too, and x lands in order.
Otherwise lift, recurse and restore
Pop the top into held, insert x into the shorter stack, then push held back. held was bigger than x and at least as big as everything under it, so putting it back on top keeps the whole stack sorted.
Code in Python, C++ and Java
Sort a stack using another stack
tmp always holds its values with the smallest on top. Each value popped from st sends every smaller value in tmp back to st, then takes its place in tmp. Pouring tmp back at the end turns it upside down, so st finishes with the largest value on top.
Common pitfalls
Sorting the wrong way round
if not st or st[-1] >= x:
st.append(x)if not st or st[-1] <= x:
st.append(x)The judge prints the stack from the top, so the expected output for [41, 3, 32, 2, 11] is [41, 32, 11, 3, 2]. That list looks descending, which tempts people to flip the comparison. Flipping it puts the smallest value on top and prints [2, 3, 11, 32, 41].
Python's default recursion limit
class Solution:
def sortStack(self, st):
...import sys
sys.setrecursionlimit(10000)
class Solution:
def sortStack(self, st):
...Python stops at about 1,000 nested calls. With 1,000 values the sorting recursion alone needs 1,000 calls, so even the already sorted stack [1, 2, ..., 1000] raises RecursionError. C++ and Java handle this depth with their default stacks.
Edge cases
[2, 1, 2]The check is <=, so an equal top stops the search at once. The second 2 is pushed straight onto the first one with no extra pops.
Every insert pushes immediately, so the work drops to O(n). The recursion is still n calls deep, because every value must be popped before any is put back.
Complexity
[3, 2, 1] written bottom to top. The space is the call stack; no other container is used.Sort a Stack FAQ
Why does the recursion go only about n calls deep, not 2n?
The sort call at depth d is the one inserting, and by then the stack below it holds only n − d values. Its insert can lift at most those n − d values, so the two kinds of call together never stack up past about n frames. Each value is either held by a sort call, held by an insert call, or sitting in the stack, never two at once.
How do you reverse a stack with the same idea?
Keep the peel step and change the insert: always push x at the very bottom. Pop everything, push x into the empty stack, and push the popped values back. Bottom-insertion turns the order around instead of sorting it.