709919. Reverse a Stack

Medium

Reverse a Stack

Slug: reverse-a-stack

Difficulty: Medium

Topic Tags: Recursion, Stack, Data Structures, Algorithms

Company Tags: None

Summary

Reverse a stack is a classic problem that involves reversing the order of elements in a stack. The key concept involved here is recursion, which allows us to solve this problem efficiently.

Detailed Explanation

To reverse a stack, we can use recursion. The basic idea is to pop all elements from the stack and push them back onto the stack in reverse order. We'll keep track of the popped elements using a temporary stack.

Here's a step-by-step breakdown:

  1. Create an empty temporary stack.
  2. Pop elements from the original stack until it becomes empty.
  3. For each popped element, push it onto the temporary stack.
  4. Once the original stack is empty, pop all elements from the temporary stack and push them back onto the original stack.

This process effectively reverses the order of the elements in the stack.

Time complexity: O(n), where n is the number of elements in the stack. Space complexity: O(n), as we're using an additional stack to store the popped elements.

Optimized Solutions

Java

View on GeeksforGeeks
public static void reverseStack(Stack<Integer> stack) {
    Stack<Integer> temp = new Stack<>();
    while (!stack.isEmpty()) {
        temp.push(stack.pop());
    }
    while (!temp.isEmpty()) {
        stack.push(temp.pop());
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.