Implement a method to insert an element at its bottom without using any other data structure
Pattern: Implementation
Pop the top, insert x at the bottom of what is left (the same problem, one smaller), and push the top back. When the stack is empty, pushing x makes it the bottom. The call stack holds the popped values.
The problem
Given a stack and a value x, put x at the bottom of the stack, keeping the other items in order, without a second
container. Stack 1, 2, 3, 4 (bottom to top) and x = 9 give 9, 1, 2, 3, 4. The function changes the stack and
returns nothing; the tests print the stack from bottom to top.
Think first
- What is the smallest stack where inserting at the bottom is easy?
- If you take the top off, what problem is left?
- Where can you keep the top while you solve it?
Hints
Brute force, and why it fails
With a second stack: pop everything into it, push x, pour back. O(n) time, O(n) extra space, but the problem forbids the extra container.
The key insight
Recursion uses the call stack as the hidden second stack. Each level holds one item and puts it back on top after the deeper levels have placed x.
Dry run
| held | 4 3 2 1 |
|---|
Stack 1, 2, 3, 4 (4 on top), x = 9. Pop 4, 3, 2, 1 down the calls.
The plan
insertAtBottom(st, x):
if st is empty: push x; return
top = pop
insertAtBottom(st, x)
push top
Complexity
- Time
O(n)- Space
O(n) call stack
Each item is popped and pushed once; the recursion is n levels deep.
Edge cases
- Empty stack: the result is just
x. - One item.
- Very deep stacks can overflow the call stack; the tests stay at 150.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public void insertAtBottom(Stack<Integer> st, int x) {
if (st.isEmpty()) { st.push(x); return; } // an empty stack: x is now the bottom
int top = st.pop(); // hold the top on the call stack
insertAtBottom(st, x);
st.push(top); // put it back above x
}
}C++
class Solution {
public:
void insertAtBottom(stack<int>& st, int x) {
if (st.empty()) { st.push(x); return; } // an empty stack: x is now the bottom
int top = st.top(); // hold the top on the call stack
st.pop();
insertAtBottom(st, x);
st.push(top); // put it back above x
}
};Python
class Solution:
def insertAtBottom(self, st: list, x: int) -> None:
if not st:
st.append(x) # an empty stack: x is now the bottom
return
top = st.pop() # hold the top on the call stack
self.insertAtBottom(st, x)
st.append(top) # put it back above xCommon mistakes
- Pushing
xbefore the recursive call, which puts it in the wrong place. - Forgetting to push the held top back.