GeeksforGeeks Medium

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.

Constraints
  • 1 <= st.size() <= 10³
  • 1 <= st[i] <= 10³
stackrecursion
Open on GeeksforGeeks ↗
02

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, push x. Otherwise pop the top, insert x lower 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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1import sys
▶2 
▶3sys.setrecursionlimit(10000)
▶4 
▶5 
▶6class Solution:
▶7 def sortStack(self, st):
▶8 if not st:
▶9 return
▶10 top = st.pop()
▶11 self.sortStack(st)
▶12 self.insert(st, top)
▶13 
▶14 def insert(self, st, x):
▶15 if not st or st[-1] <= x:
▶16 st.append(x)
▶17 return
▶18 held = st.pop()
▶19 self.insert(st, x)
▶20 st.append(held)
stackheld by calls314bottom2sort callpop 2 → this call holds it
stack[3, 1, 4]bottom → top
x—value being placed
Pop the top value 2. The only place allowed to keep it is the current call's local variable, so it waits there while a deeper call sorts the 3 values below.
stackheld by calls31bottom2sort call4sort callpop 4 → this call holds it
stack[3, 1]bottom → top
x—value being placed
Pop the top value 4. The only place allowed to keep it is the current call's local variable, so it waits there while a deeper call sorts the 2 values below.
stackheld by calls3bottom2sort call4sort call1sort callpop 1 → this call holds it
stack[3]bottom → top
x—value being placed
Pop the top value 1. The only place allowed to keep it is the current call's local variable, so it waits there while a deeper call sorts the 1 value below.
stackheld by callsemptybottom2sort call4sort call1sort call3sort callpop 3 → this call holds it
stack[]bottom → top
x—value being placed
Pop the top value 3. The only place allowed to keep it is the current call's local variable, so it waits there while a deeper call sorts the 0 values below.
stackheld by callsemptybottom2sort call4sort call1sort call3sort callstack empty → start putting values back
stack[]bottom → top
x—value being placed
An empty stack is already sorted, so the deepest call returns. Every call now gets its value back, one at a time from the deepest, and has to slot it into a stack that is already sorted.
stackheld by calls3bottom2sort call4sort call1sort callstack empty → push 3
stack[3]bottom → top
x—value being placed
The stack is empty, so 3 goes straight in. With nothing below it, it is trivially in order.
stackheld by callsemptybottomx12sort call4sort call3insert call3 is bigger than 1 → lift it out
stack[]bottom → top
x1value being placed
3 on top is bigger than 1, so 1 cannot sit above it. Pop 3 into a new insert call and keep looking lower. The bigger value must go back on top later.
stackheld by calls1bottom2sort call4sort call3insert callstack empty → push 1
stack[1]bottom → top
x—value being placed
The stack is empty, so 1 goes straight in. With nothing below it, it is trivially in order.
stackheld by calls13bottom2sort call4sort callpush 3 back on top
stack[1, 3]bottom → top
x—value being placed
That insert call now returns and pushes 3 back. It is bigger than everything under it, so the stack stays sorted.
stackheld by calls134bottom2sort calltop 3 is not bigger → push 4
stack[1, 3, 4]bottom → top
x—value being placed
The top 3 is not bigger than 4. Nothing below the top is bigger either, so 4 belongs right here. Pushing it keeps the stack sorted.
stackheld by calls13bottomx24insert call4 is bigger than 2 → lift it out
stack[1, 3]bottom → top
x2value being placed
4 on top is bigger than 2, so 2 cannot sit above it. Pop 4 into a new insert call and keep looking lower. The bigger value must go back on top later.
stackheld by calls1bottomx24insert call3insert call3 is bigger than 2 → lift it out
stack[1]bottom → top
x2value being placed
3 on top is bigger than 2, so 2 cannot sit above it. Pop 3 into a new insert call and keep looking lower. The bigger value must go back on top later.
stackheld by calls12bottom4insert call3insert calltop 1 is not bigger → push 2
stack[1, 2]bottom → top
x—value being placed
The top 1 is not bigger than 2. Nothing below the top is bigger either, so 2 belongs right here. Pushing it keeps the stack sorted.
stackheld by calls123bottom4insert callpush 3 back on top
stack[1, 2, 3]bottom → top
x—value being placed
That insert call now returns and pushes 3 back. It is bigger than everything under it, so the stack stays sorted.
stackheld by calls1234bottomnonepush 4 back on top
stack[1, 2, 3, 4]bottom → top
x—value being placed
That insert call now returns and pushes 4 back. It is bigger than everything under it, so the stack stays sorted.
stackheld by calls1234bottomnonesorted: smallest at the bottom, largest on top
stack[1, 2, 3, 4]bottom → top
x—value being placed
Every call has placed its value and returned. Read from the top, the stack is [4, 3, 2, 1]: the largest value is on top, which is the order the problem asks for.
05

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.

▶1class Solution:
▶2 def sortStack(self, st):
▶3 tmp = []
▶4 while st:
▶5 x = st.pop()
▶6 while tmp and tmp[-1] < x:
▶7 st.append(tmp.pop())
▶8 tmp.append(x)
▶9 while tmp:
▶10 st.append(tmp.pop())
06

Common pitfalls

Sorting the wrong way round

✗ Wrong
if not st or st[-1] >= x:
    st.append(x)
✓ Right
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

✗ Wrong
class Solution:
    def sortStack(self, st):
        ...
✓ Right
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.

07

Edge cases

Equal values, such as [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.

A stack that is already sorted

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.

08

Complexity

Time
O(n²)
Space
O(n)
Inserting into a stack of k values can lift all k, so the worst case adds up to 1 + 2 + … + (n − 1). That happens when the smallest value starts on top, as in [3, 2, 1] written bottom to top. The space is the call stack; no other container is used.
09

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.