StackMedium
Reverse Stack Visualizer
What is Reverse Stack
The values are given from bottom to top. Reversing the stack makes the old top into the new bottom.
- Hold values aside pop everything into a second list.
- Push them back the first value popped was the old top, so it is pushed first and ends on the bottom.
- Same order printed the judge prints the reversed stack from bottom to top.
Approach
A second stack (or the call stack of a recursive insert) reverses the order because each pop hands you the latest value first.
Visualization & algorithm
Pop everything, then push it back
held = []
while stack: held.append(stack.pop())
held is the new bottom-to-top
the old top is now the bottom
Step 0/0
Answer —
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|
| Time | O(n) | Each value moves twice. |
| Extra space | O(n) | The held values. |
Implementation
def solve(self, nums):
# nums is bottom to top; return the reversed bottom to top
return list(reversed(nums))