Delete the Middle Element of a Stack Using Recursion
Implement deleteMiddleRecursive
Given a stack of integers, delete the middle element — for an odd-length stack, the exact middle; for an even-length stack, the one closer to the bottom of the two middle elements — using only push, pop, top, and isEmpty, with no other explicit data structure or direct indexing.
Since the middle position can't be accessed directly under this constraint, the recursion reaches it a different way: by counting. Popping one element per level of recursive descent means the depth of recursion IS the count of elements removed from the top so far — so descending exactly ⌊n/2⌋ levels guarantees the current top is precisely the target element, without ever computing or storing an index. Pop and discard it there; then, as the recursion unwinds, every other held-aside value gets pushed back on top, restoring the stack everywhere except at the one dropped position.
Example 1:
Input: stack = [7,3,9,2,8]
Output: [7,3,2,8]
Example 2:
Input: stack = [9,4,6,2,7,1]
Output: [9,4,2,7,1]
Example 3:
Input: stack = [1,2,3,4]
Output: [1,3,4]
+ 2 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ stack.length ≤ 11 - ●
stack is given bottom-to-top (index 0 is the bottom, the last index is the top) - ●
-100 ≤ stack[i] ≤ 100 - ●
The 'middle' element, counted 1-indexed from the bottom, is at position ⌈n/2⌉ — for an even-length stack, this is the one closer to the bottom of the two middle elements - ●
Only push, pop, top/peek, and isEmpty are considered valid stack operations for the intended (recursive) technique — no other explicit data structure or index-based access may be used
stack =
[7, 3, 9, 2, 8]