Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Last active September 29, 2024 18:21
Show Gist options
  • Save KeshariPiyush24/6e045acc25f785926a8c65eebc8f30a2 to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/6e045acc25f785926a8c65eebc8f30a2 to your computer and use it in GitHub Desktop.
Reverse A Stack Using Recursion

Reversing a Stack using Recursion

Intuition

The core idea behind reversing a stack using recursion is to:

  1. Remove elements from the stack one by one.
  2. Recursively reverse the remaining stack.
  3. Insert the removed element at the bottom of the reversed stack.

This approach leverages the call stack to temporarily hold the elements while reversing their order, allowing for an in-place reversal without additional data structures.

Algorithm

The algorithm uses two main recursive functions:

  1. reverseStack: Reverses the entire stack.
  2. insertAtBottom: Inserts an element at the bottom of the stack.

reverseStack

  • Base case: If the stack is empty or has only one element, it's already reversed.
  • Recursive case:
    1. Remove the top element.
    2. Reverse the remaining stack.
    3. Insert the removed element at the bottom of the reversed stack.

insertAtBottom

  • Base case: If the stack is empty, push the item.
  • Recursive case:
    1. Remove the top element.
    2. Recursively insert the item at the bottom.
    3. Push back the removed top element.

Time Complexity

  • O(n), where n is the number of elements in the stack.
  • For each element, we make 1 call to insertAtBottom and 1 call to reverseStack.

Space Complexity

  • O(n), where n is the number of elements in the stack.
  • The maximum depth of the recursive call stack is n.

Java Implementation

import java.util.Stack;

public class ReverseStack {
    // Method to reverse the stack
    public static void reverseStack(Stack<Integer> stack) {
        // Base case: if the stack is empty or has only one element, it's already reversed
        if (stack.isEmpty() || stack.size() == 1) {
            return;
        }
        
        // Remove the top element
        int top = stack.pop();
        
        // Recursively reverse the remaining stack
        reverseStack(stack);
        
        // Insert the top element at the bottom of the reversed stack
        insertAtBottom(stack, top);
    }
    
    // Helper method to insert an element at the bottom of the stack
    private static void insertAtBottom(Stack<Integer> stack, int item) {
        // Base case: if the stack is empty, push the item
        if (stack.isEmpty()) {
            stack.push(item);
            return;
        }
        
        // Remove the top element
        int top = stack.pop();
        
        // Recursively insert the item at the bottom
        insertAtBottom(stack, item);
        
        // Push back the top element
        stack.push(top);
    }
    
    // Main method to test the reverseStack function
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        
        System.out.println("Original stack: " + stack);
        reverseStack(stack);
        System.out.println("Reversed stack: " + stack);
    }
}

Trade-offs and Considerations

  • This recursive solution, while elegant, is not the most efficient approach for reversing a stack.
  • An iterative solution using an additional stack could achieve O(n) time complexity with O(n) space complexity.
  • The recursive approach is valuable for understanding recursion and stack operations, but may not be suitable for large stacks due to the risk of stack overflow.

Conclusion

The recursive stack reversal algorithm demonstrates a clever use of the call stack to reverse elements. However, for practical applications, especially with large datasets, more efficient iterative solutions should be considered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment