Reverse a Stack Without Extra Space | Java Recursive Solution
Reverse a Stack Without Extra Space | Java Recursive Solution

Reverse a Stack Without Extra Space | Java Recursive Solution

Learn how to reverse a stack using recursion without extra space. Step-by-step explanation, Java code, dry run, and interview tips included.

7 views
0
0
Listen to articleAudio version

Introduction

Reversing a stack is a classic data structures problem that frequently appears in coding interviews and competitive programming. While it may seem straightforward, the challenge lies in reversing the stack without using any additional data structure.

This problem is a great way to understand the power of recursion and stack manipulation.

In this article, we will explore an intuitive recursive approach, understand how it works step by step, and also briefly discuss alternative methods.

Link of Problem: GeeksforGeeks – Reverse a Stack

Problem Statement

You are given a stack st[]. The task is to reverse the stack.

Important Notes

  1. The input array represents the stack from bottom to top
  2. The last element is considered the top
  3. Output should display elements from top to bottom after reversal

Examples

Example 1

Input:

st = [1, 2, 3, 4]

Output:

[1, 2, 3, 4]

Explanation:

After reversing, the internal order becomes [4, 3, 2, 1],

so when printed from top → bottom, it appears as [1, 2, 3, 4].

Example 2

Input:

st = [3, 2, 1]

Output:

[3, 2, 1]

Explanation:

Reversed stack becomes [1, 2, 3] internally.

Key Insight

A stack only allows:

  1. push() → insert at top
  2. pop() → remove from top

Challenge

We cannot directly insert an element at the bottom of the stack.

Solution Strategy

Use recursion to:

  1. Remove all elements from the stack
  2. Insert each element back at the bottom

This effectively reverses the stack.

Approach: Recursive Solution

Idea

  1. Pop the top element
  2. Reverse the remaining stack recursively
  3. Insert the popped element at the bottom

Code (Java)

import java.util.Stack;

class Solution {

static void rever(Stack<Integer> s) {
if (s.size() == 1) return;

int temp = s.pop();

// Reverse remaining stack
rever(s);

// Insert element at bottom
insre(s, temp);
}

static void insre(Stack<Integer> s, int val) {
// Base condition: empty stack
if (s.empty()) {
s.push(val);
return;
}

int temp = s.pop();

// Recursive call
insre(s, val);

// Push back previous elements
s.push(temp);
}

public static void reverseStack(Stack<Integer> st) {
rever(st);
}
}

Step-by-Step Dry Run

Let’s take:

Stack (bottom → top): [1, 2, 3, 4]

Execution Flow:

  1. Pop 4 → reverse [1, 2, 3]
  2. Pop 3 → reverse [1, 2]
  3. Pop 2 → reverse [1]
  4. Insert elements at bottom in order

Final Stack:

[4, 3, 2, 1]

Complexity Analysis

  1. Time Complexity: O(n²)
  2. Each insertion at bottom takes O(n)
  3. Auxiliary Space: O(n)
  4. Due to recursion call stack

Why This Approach Works

  1. Recursion helps access deeper elements of the stack
  2. The helper function inserts elements at the bottom
  3. Maintains order while reversing without extra structures

Alternative Approaches

1. Using Two Stacks

  1. Transfer elements between stacks multiple times
  2. Easy but uses extra space

2. Using Array/List

  1. Store elements in a list
  2. Push them back into stack

⚠️ These methods violate the constraint of not using extra data structures.

Key Takeaways

  1. Stack problems often require creative recursion
  2. Reversing a stack without extra space is a common interview pattern
  3. Understanding insert at bottom is crucial
  4. Time complexity is higher due to repeated insert operations

When This Problem Is Asked

This question is commonly seen in:

  1. Technical interviews
  2. Stack and recursion problem sets
  3. Platforms like GeeksforGeeks

It evaluates:

  1. Understanding of stack operations
  2. Recursive thinking
  3. Problem-solving under constraints

Conclusion

Reversing a stack without using extra space is a great example of how recursion can simplify complex constraints. While the solution may not be the most optimal in terms of time complexity, it is elegant and widely accepted in interviews.

Mastering this pattern will help you solve many similar problems involving stack manipulation.

Frequently Asked Questions (FAQs)

1. Why is the time complexity O(n²)?

Because inserting an element at the bottom takes O(n), and this is done for each element.

2. Can this be optimized further?

Not without using extra data structures. The recursive approach is optimal under constraints.

3. What is the key concept to learn here?

Understanding how to insert an element at the bottom of a stack using recursion.

Ai Assistant Kas