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:
- Create an empty temporary stack.
- Pop elements from the original stack until it becomes empty.
- For each popped element, push it onto the temporary stack.
- 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
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());
}
}