Problem
You are given a stack and you need to reverse it in place using recursion. You can only use the following Stack ADT functions:
push(x)
: Add an elementx
to the top of the stack.pop()
: Remove the element at the top of the stack.peek()
: Get the element at the top of the stack without removing it.isEmpty()
: Check whether the stack is empty.
The task is to reverse the stack such that the bottom-most element becomes the top-most, and the top-most element becomes the bottom-most, while using only the allowed stack operations and recursion.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Using Recursion
To reverse a stack in place using recursion, the key is to use an auxiliary recursive function to recursively pop elements from the stack until the stack is empty, and then use another recursive helper function to insert the elements at the bottom of the stack instead of the top. This ensures that the order of elements gets reversed.
Approach
- Reverse Function: This function uses recursion to pop all elements until the stack becomes empty. For each element popped, we call the Insert at Bottom function to insert the element at the bottom of the stack.
- Insert at Bottom Function: This auxiliary function ensures that given an element
x
, it recursively pops elements until the stack becomes empty, then pushesx
, and subsequently pushes all elements back in the order they were popped.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
as each call toreverse
causes a sequence of insertions which can takeO(n)
steps due to recursive inserts, withn
stack elements causing total complexity ofO(n^2)
. - 🧺 Space complexity:
O(n)
, as the space used by the call stack due to recursion will be at most the depth of the recursion, which isO(n)
forn
elements in the stack.