Reverse a stack using recursion

Pattern: Implementation

easy

Pop the top, reverse the rest recursively, then insert the old top at the bottom. Inserting at the bottom is itself a small recursion. The total cost is O(n²) because each of n inserts walks the stack.

The problem

Reverse a stack in place using recursion and no second container. Stack 1, 2, 3, 4 (bottom to top) becomes 4, 3, 2, 1. The function returns nothing; the tests print the stack from bottom to top.

Think first

  • If the rest of the stack is already reversed, where does the old top belong?
  • Which earlier problem puts an item at the bottom?
  • How deep does the recursion go?

Hints

    Brute force, and why it fails

    With a second container: pop everything into a queue, then push back from the queue's front. O(n), but it uses extra space.

    The key insight

    Reverse = take the top off, reverse the rest, put the top at the bottom. All the holding is done by the call stack.

    Dry run

    10 
    21 
    32 
    held3 2 1

    Stack 1, 2, 3 (3 on top). reverse pops 3, then 2, then 1, leaving an empty stack.

    Step 1 of 4

    The plan

    reverse(st):
        if st is empty: return
        top = pop
        reverse(st)
        insertAtBottom(st, top)
    

    Complexity

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

    Each of the n levels calls insertAtBottom, which walks the current stack: 1 + 2 + … + n.

    Edge cases

    • Empty or one item: unchanged.
    • Repeated values.
    • Deep stacks: the tests stay at 120.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public void reverseStack(Stack<Integer> st) {
            if (st.isEmpty()) return;
            int top = st.pop();
            reverseStack(st);                       // reverse everything below
            insertAtBottom(st, top);                // and the old top becomes the new bottom
        }
    
        private void insertAtBottom(Stack<Integer> st, int x) {
            if (st.isEmpty()) { st.push(x); return; }
            int top = st.pop();
            insertAtBottom(st, x);
            st.push(top);
        }
    }

    C++

    class Solution {
    public:
        void reverseStack(stack<int>& st) {
            if (st.empty()) return;
            int top = st.top();
            st.pop();
            reverseStack(st);                       // reverse everything below
            insertAtBottom(st, top);                // and the old top becomes the new bottom
        }
    
        void insertAtBottom(stack<int>& st, int x) {
            if (st.empty()) { st.push(x); return; }
            int top = st.top();
            st.pop();
            insertAtBottom(st, x);
            st.push(top);
        }
    };

    Python

    class Solution:
        def reverseStack(self, st: list) -> None:
            if not st:
                return
            top = st.pop()
            self.reverseStack(st)                   # reverse everything below
            self.insert_at_bottom(st, top)          # and the old top becomes the new bottom
    
        def insert_at_bottom(self, st: list, x: int) -> None:
            if not st:
                st.append(x)
                return
            top = st.pop()
            self.insert_at_bottom(st, x)
            st.append(top)

    Common mistakes

    • Pushing the top back on top instead of inserting it at the bottom, which leaves the stack unchanged.
    • Calling reverse inside insertAtBottom.

    Similar problems