In this article, we walk through the classic problem of deleting the middle element from a stack using pure recursion. The approach leverages the call stack itself rather than iterative loops or an auxiliary data structure.
Understanding the Problem
Given a stack of integers, the task is to remove the middle element. If the stack has an even number of elements, the lower middle is considered (e.g., for size 4, the element at position 2 from top is removed).
Recursive Strategy
The key insight is to use recursion to pop elements until we reach the middle, then discard that element and push back the previously popped elements. This is done without any explicit extra stack.
Steps:
- Define a recursive function that takes the stack and an index (or size) parameter.
- Base case: If the recursion reaches the middle, pop the current top and return.
- Otherwise, pop the top element, recursively call the function on the remaining stack, then push back the saved element.
Implementation
Below are implementations in Java, Python, and C++.
Java
public static void deleteMiddle(Stack<Integer> stack, int size, int current) {
if (current == size / 2) {
stack.pop();
return;
}
int top = stack.pop();
deleteMiddle(stack, size, current + 1);
stack.push(top);
}
Python
def delete_middle(stack, size, current=0):
if current == size // 2:
stack.pop()
return
top = stack.pop()
delete_middle(stack, size, current + 1)
stack.append(top)
C++
void deleteMiddle(stack<int>& s, int size, int current = 0) {
if (current == size / 2) {
s.pop();
return;
}
int top = s.top(); s.pop();
deleteMiddle(s, size, current + 1);
s.push(top);
}
Time and Space Complexity
- Time Complexity: O(n), where n is the number of elements in the stack.
- Space Complexity: O(n) due to recursion stack.
Key Takeaway
This problem demonstrates how recursion can effectively manipulate a stack without extra space, reinforcing the power of the call stack in problem-solving.
This article is part of the Recursion Patterns series by RisingBrain.