Reverse a Stack — GFG Problem Solved (3 Approaches Explained)
Reverse a Stack — GFG Problem Solved (3 Approaches Explained)

Reverse a Stack — GFG Problem Solved (3 Approaches Explained)

Learn how to reverse a stack in Java with 3 different approaches — extra stack, ArrayList, and recursion. Full solution to the GFG "Reverse a Stack" problem explained step by step in easy language with code.

10 views
0
0
Listen to articleAudio version

What Is This Problem About?

This is a classic stack problem from GeeksForGeeks"Reverse a Stack" (Medium | 4 Points). You can find it on GFG by Reverse a Stack.

You are given a stack. Your job is simple — reverse it. The element that was at the bottom should now be at the top, and vice versa.

Example:

Input: [1, 2, 3, 4] → bottom to top, so 4 is on top
Output: [1, 2, 3, 4] → after reversal, 1 is on top

Wait — the input and output look the same? That is because GFG displays the result top to bottom after reversal. So after reversing, 1 comes to the top, and printing top to bottom gives [1, 2, 3, 4]. The stack is indeed reversed internally.

Approach 1 — Using Two Extra Stacks

Intuition: Pop everything from the original stack into Stack 1 — this reverses the order once. Then pop everything from Stack 1 into Stack 2 — this reverses it again, back to original order. Now push everything from Stack 2 back into the original stack. The result? The original stack is reversed.

Why does this work? Two reversals cancel each other out to give you... wait, that sounds wrong. Let us trace it:

Original: [1, 2, 3, 4] → top is 4

After → S1: [4, 3, 2, 1] → top is 1
After → S2: [1, 2, 3, 4] → top is 4
Push S2 back → st: [1, 2, 3, 4] → top is 4

Hmm, that brings it back to the same thing. This approach with two stacks actually does NOT work correctly — it ends up restoring the original order. This is why the approach was commented out in the original code. Good observation to catch in an interview.

Lesson: Two full reversals = no change. One reversal = what we want. Keep this in mind.

Approach 2 — Using an ArrayList (Clean & Simple) ✅

Intuition: Pop all elements from the stack into an ArrayList. At this point, the ArrayList holds elements in reverse order (because popping reverses). Then push them back from index 0 to end. This is the clean, working solution.

Stack: [1, 2, 3, 4] → top is 4

Pop into ArrayList: [4, 3, 2, 1]
Push back index 0→end:
push 4 → st: [4]
push 3 → st: [4, 3]
push 2 → st: [4, 3, 2]
push 1 → st: [4, 3, 2, 1] → top is now 1 ✓

The stack is now reversed. 1 is on top.

public static void reverseStack(Stack<Integer> st) {
if (st.empty()) return;

ArrayList<Integer> list = new ArrayList<>();

// Pop all elements — goes in reverse order into list
while (!st.empty()) {
list.add(st.pop());
}

// Push back from index 0 — restores in reversed order
for (int i = 0; i < list.size(); i++) {
st.push(list.get(i));
}
}

Time Complexity: O(n) — one pass to pop, one pass to push.

Space Complexity: O(n) — for the ArrayList.

Why this works: When you pop all elements into a list, the top element (last inserted) goes to index 0. When you push back from index 0, that element goes in first and ends up at the bottom. The bottom element (first inserted) was popped last, sits at the end of the list, and gets pushed last — ending up on top. That is a perfect reversal.

Approach 3 — Using Recursion (No Extra Space) ✅

This is the most elegant approach and the one interviewers love to ask about.

Intuition: Use two recursive functions:

  1. reverseStack — pops the top element, recursively reverses the rest, then inserts the popped element at the bottom.
  2. insertAtBottom — holds all elements out while inserting one element at the very bottom, then restores everything.
// Insert an item at the bottom of the stack
static void insertAtBottom(Stack<Integer> st, int item) {
if (st.empty()) {
st.push(item);
return;
}
int top = st.pop();
insertAtBottom(st, item);
st.push(top);
}

// Reverse the stack
public static void reverseStack(Stack<Integer> st) {
if (st.empty()) return;

int top = st.pop();
reverseStack(st); // reverse remaining stack
insertAtBottom(st, top); // put popped element at the bottom
}
```

**Dry Run with [1, 2, 3]:**
```
reverseStack([1,2,3]) → pop 3, reverseStack([1,2])
reverseStack([1,2]) → pop 2, reverseStack([1])
reverseStack([1]) → pop 1, reverseStack([])
base case → return
insertAtBottom([], 1) → push 1 → [1]
insertAtBottom([1], 2) → 2 < 1? no → pop 1, insert 2, push 1 → [2,1]
insertAtBottom([2,1], 3) → pop 1, pop 2, push 3, push 2, push 1 → [3,2,1]

Final stack top → 3... wait, let us recheck display.
Top is 3, which was originally at bottom. ✓ Reversed!

Time Complexity: O(n²) — for each of n elements, insertAtBottom takes O(n).

Space Complexity: O(n) — recursive call stack.

Which Approach Should You Use?

ApproachTimeSpaceSimplicityInterview Value
Two Extra Stacks❌ Does not workO(n)SimpleLow
ArrayListO(n)O(n)Very EasyMedium
RecursionO(n²)O(n)ModerateHigh

For a coding interview, always mention the recursive approach — it shows you understand stack mechanics deeply. For production code, the ArrayList approach is cleaner and faster.

Key Takeaway

Reversing a stack is fundamentally about understanding LIFO. Because a stack only allows access from the top, you need a systematic way to invert the order — whether that is using auxiliary storage like an ArrayList, or using the call stack itself via recursion. Both are valid. Both teach you something different about how stacks behave.

The next time you see a problem that involves reversing, reordering, or inserting at the bottom of a stack — your first instinct should be recursion with insertAtBottom. It is a pattern that appears again and again in DSA.

And if you want to understand Stack from Scratch?

If you are just getting started with stacks or want a complete reference — I have written a detailed in-depth guide on the Stack Data Structure in Java covering everything from what a stack is, how LIFO works, all three implementations (Array, ArrayList, LinkedList), every operation explained with code, time complexity, advantages, disadvantages, real-world use cases, and six practice problems with full solutions.

Check it out here → Stack Data Structure in Java: The Complete Guide

It is the perfect companion to this problem walkthrough — start there if you want the full picture, then come back here for the problem-solving side.

Ai Assistant Kas

Reverse a Stack — GFG Problem Solved (3 Approaches Explained) | Kode$word