Sort a Stack using recursion

Pattern: Implementation

easy

Pop the top, sort the rest recursively, then insert the old top into its place: pop larger items off, push it, and put them back. The result has the largest on top. This is insertion sort done with the call stack.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Sort a stack so that the largest value is on top, using recursion and no second container. Stack 11, 2, 32, 3, 41 (bottom to top) becomes 2, 3, 11, 32, 41. The function returns nothing; the tests print the stack from bottom to top.

The catalogue has no practice link for this one.

Think first

  • If everything below the top is sorted, where does the old top go?
  • How do you reach that place in a stack?
  • How does this compare with insertion sort?

Hints

    Brute force, and why it fails

    Pop everything into a list, sort it and push it back: O(n log n), but it uses another container.

    The key insight

    Two recursions: sortStack peels items off, and insertSorted slides each one back into a sorted stack.

    Dry run

    110 
    21 
    322 
    33 
    414 
    held41 3 32 2

    Stack 11, 2, 32, 3, 41 (41 on top). sortStack pops 41, 3, 32, 2, leaving 11.

    Step 1 of 5

    The plan

    sortStack(st):
        if st is empty: return
        top = pop; sortStack(st); insertSorted(st, top)
    insertSorted(st, x):
        if st is empty or st.top <= x: push x; return
        t = pop; insertSorted(st, x); push t
    

    Complexity

    Time
    O(n²)
    Space
    O(n) call stack

    Each insert can walk the whole sorted stack, like insertion sort.

    Edge cases

    • Already sorted: each insert goes straight on top.
    • Reverse sorted: the worst case.
    • Equal values: <= keeps it simple.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public void sortStack(Stack<Integer> st) {
            if (st.isEmpty()) return;
            int top = st.pop();
            sortStack(st);                          // sort the rest: biggest on top
            insertSorted(st, top);                  // then slide top into its place
        }
    
        private void insertSorted(Stack<Integer> st, int x) {
            if (st.isEmpty() || st.peek() <= x) { st.push(x); return; }   // x belongs on top here
            int top = st.pop();                     // a bigger value must stay above x
            insertSorted(st, x);
            st.push(top);
        }
    }

    C++

    class Solution {
    public:
        void sortStack(stack<int>& st) {
            if (st.empty()) return;
            int top = st.top();
            st.pop();
            sortStack(st);                          // sort the rest: biggest on top
            insertSorted(st, top);                  // then slide top into its place
        }
    
        void insertSorted(stack<int>& st, int x) {
            if (st.empty() || st.top() <= x) { st.push(x); return; }   // x belongs on top here
            int top = st.top();                     // a bigger value must stay above x
            st.pop();
            insertSorted(st, x);
            st.push(top);
        }
    };

    Python

    class Solution:
        def sortStack(self, st: list) -> None:
            if not st:
                return
            top = st.pop()
            self.sortStack(st)                      # sort the rest: biggest on top
            self.insert_sorted(st, top)             # then slide top into its place
    
        def insert_sorted(self, st: list, x: int) -> None:
            if not st or st[-1] <= x:
                st.append(x)                        # x belongs on top here
                return
            top = st.pop()                          # a bigger value must stay above x
            self.insert_sorted(st, x)
            st.append(top)

    Common mistakes

    • Flipping the comparison to >=, which puts the smallest value on top instead.
    • Forgetting to push the held value back after the inner call.

    Similar problems