How to sort a stack using only stack operations?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Sorting a stack is a classic interview and data structure exercise because you only get top access through push and pop. Without random index access, standard array sort patterns do not apply directly. The usual solution uses one auxiliary stack and only legal stack operations.
Problem Constraints and Sorting Goal
Assume you are given one stack and can use another stack as temporary storage. Allowed operations are push, pop, peek, and empty check. The goal is often to place the smallest element on top, though some variants expect the largest on top.
For clarity in this article, we will sort so the smallest element ends up on top of the original stack.
Two-Stack Insertion Style Algorithm
The algorithm is similar to insertion sort:
- Pop one element from input stack into
temp. - Move larger elements from auxiliary stack back to input stack.
- Push
tempinto auxiliary stack in sorted position. - Repeat until input stack is empty.
- Move everything back from auxiliary to input.
Python example using lists as stacks:
Output:
Because top is on the right, the final rightmost value 1 is the smallest item on top.
Step Through a Small Example
Take input stack right to left top order from [3, 5, 1, 4, 2]:
- Pop
2, aux becomes[2]. - Pop
4, aux top is2, push4, aux becomes[2, 4]. - Pop
1, move4and2back, then push1so aux becomes[1]. - Continue until input is empty.
- Move aux back to input to restore one sorted stack.
The key invariant is: auxiliary stack remains sorted at all times.
Complexity and Practical Use
Worst case time complexity is quadratic, written as O(n^2), because each element may move between stacks multiple times. Space complexity is linear, written as O(n), for the auxiliary stack.
Even with non optimal asymptotic complexity, this method is still useful when:
- You must respect strict stack interface constraints.
- Input size is moderate.
- Simplicity and correctness are more important than peak speed.
If you can access array indices directly, standard sort methods are usually faster and simpler.
Recursive Variant Without Explicit Second Stack
Some problem statements allow recursion and count the call stack as implicit storage. In that version, recursively pop all elements, then insert each element back into the correct sorted position.
This variant is elegant but can hit recursion limits on large input in some languages.
Common Pitfalls
- Losing track of top orientation in examples, which makes result checks look wrong.
- Forgetting to move data back from auxiliary stack to original stack.
- Using comparisons in the wrong direction and ending with reverse order.
- Assuming recursion is free for very large stacks. Deep recursion may fail.
- Mixing queue operations with stack operations, which breaks constraints.
Summary
- Sort a stack under stack-only rules by using an auxiliary stack.
- Maintain a sorted invariant in the auxiliary stack as you process items.
- Move elements back to return a single sorted original stack.
- Expect
O(n^2)time andO(n)additional space. - Validate top direction in tests so order requirements are unambiguous.
Related reading
- How to sort a string list consists of digits and alphabets in Java?
- How to sort an array of custom objects by property value?
- How to sort an array of integers?
- How to sort an array of integers faster than quicksort?
- How to sort an object array by date property?
- How to sort array suffixes in block sorting
- How to sort an ArrayList in Java
- How to sort an IEnumerablestring

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.