DEV Community

Jaspreet singh
Jaspreet singh

Posted on

Sort a Stack | Recursion

Problem Statement

Given a stack of integers, sort the stack such that:

Smallest element at the bottom

Largest element at the top
Enter fullscreen mode Exit fullscreen mode

You are allowed to use only stack operations.


Brute Force Intuition

In an interview, you can explain it like this:

Pop every element into an array, sort the array, and push the elements back into the stack.

This works but uses an extra array, violating the spirit of the problem.

Complexity

  • Time Complexity: O(N log N)
  • Space Complexity: O(N)

Brute Force Code

class Solution {

    public void sortStack(Stack<Integer> st) {

        int[] arr = new int[st.size()];

        int i = 0;

        while (!st.isEmpty()) {
            arr[i++] = st.pop();
        }

        Arrays.sort(arr);

        for (int num : arr) {
            st.push(num);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Moving Towards the Optimal Approach

Instead of using an extra array, can we use recursion itself as the temporary storage?

Yes.

The idea is:

Pop one element

↓

Sort remaining stack

↓

Insert the popped element
at its correct position
Enter fullscreen mode Exit fullscreen mode

Pattern Recognition

Whenever you see:

  • Stack
  • Only stack operations allowed
  • No extra data structure

Think:

Recursion + Backtracking


Key Observation

Suppose the stack is:

3
1
4
2
Enter fullscreen mode Exit fullscreen mode

Pop:

3
Enter fullscreen mode Exit fullscreen mode

Now recursively sort:

1
4
2
Enter fullscreen mode Exit fullscreen mode

After it becomes sorted:

1
2
4
Enter fullscreen mode Exit fullscreen mode

Insert:

3
Enter fullscreen mode Exit fullscreen mode

at its correct position.


Optimal Approach

Create two recursive functions:

sort()

Pop Top

↓

Sort Remaining Stack

↓

Insert Element Back
Enter fullscreen mode Exit fullscreen mode

insert()

If:

Stack Empty

OR

Top <= Current
Enter fullscreen mode Exit fullscreen mode

Push directly.

Otherwise:

Pop

↓

Insert Recursively

↓

Push Back
Enter fullscreen mode Exit fullscreen mode

Optimal Java Solution

class Solution {

    public void sortStack(Stack<Integer> st) {

        if (st.isEmpty())
            return;

        int top = st.pop();

        sortStack(st);

        insert(st, top);
    }

    private void insert(Stack<Integer> st, int num) {

        if (st.isEmpty() || st.peek() <= num) {

            st.push(num);
            return;
        }

        int top = st.pop();

        insert(st, num);

        st.push(top);
    }
}
Enter fullscreen mode Exit fullscreen mode

Dry Run

Input

Top

2
4
1
3
Enter fullscreen mode Exit fullscreen mode

Step 1

Pop:

2
Enter fullscreen mode Exit fullscreen mode

Recursively sort:

4
1
3
Enter fullscreen mode Exit fullscreen mode

Step 2

Eventually stack becomes:

1
3
4
Enter fullscreen mode Exit fullscreen mode

Now insert:

2
Enter fullscreen mode Exit fullscreen mode

Pop:

4
Enter fullscreen mode Exit fullscreen mode

Pop:

3
Enter fullscreen mode Exit fullscreen mode

Insert:

2
Enter fullscreen mode Exit fullscreen mode

Push back:

3

4
Enter fullscreen mode Exit fullscreen mode

Final Stack:

Top

4
3
2
1
Enter fullscreen mode Exit fullscreen mode

Largest element remains on top.


Why Recursion Works?

Recursion automatically stores removed elements on the function call stack.

After sorting the smaller stack:

Insert every removed element
back into its correct position.
Enter fullscreen mode Exit fullscreen mode

This eliminates the need for an extra array.


Complexity Analysis

Metric Complexity
Time Complexity O(N²)
Space Complexity O(N) (Recursion Stack)

Interview One-Liner

Recursively sort the smaller stack, then insert the removed element back into its correct position using another recursive function.


Pattern Learned

Stack
+
No Extra Data Structure
+
Maintain Order

=> Recursion
Enter fullscreen mode Exit fullscreen mode

Similar Problems

  • Sort a Stack
  • Reverse a Stack
  • Delete Middle Element of Stack
  • Reverse Stack Using Recursion

Memory Trick

Think:

Pop Everything

↓

Sort Smaller Stack

↓

Insert Back
Enter fullscreen mode Exit fullscreen mode

Mental Model

Sort Stack

↓

Remove Top

↓

Sort Remaining

↓

Insert at Correct Position
Enter fullscreen mode Exit fullscreen mode

Whenever you hear:

"Sort a stack without using another data structure"

your brain should immediately think:

Recursion + Insert in Sorted Order

Top comments (0)