Flip a Stack's Order Using Pure Recursion

Implement reverseStackRecursive

Given a stack of integers, reverse its contents completely, using only push, pop, top, and isEmpty — no other explicit data structure, and no loops for the reversal logic itself. The recursive technique builds directly on "insert a value at the bottom of a stack": pop the top element, recursively reverse whatever remains beneath it, then insert the popped element at the very bottom of that now-reversed remainder. Reaching the empty stack (the base case) is where the unwinding starts — each level restores its held-aside value to the bottom, one at a time, until the whole stack has flipped end to end. It's worth being upfront about the cost of this elegance: because inserting at the bottom is itself an O(n) recursive walk, and it happens once per level of the outer recursion, the total work comes out to O(n²) — genuinely slower than simply copying into a second array, which is the better choice whenever the "no auxiliary structure" constraint doesn't actually apply.

Example 1:

Input: stack = [1,2,3,4]

Output: [4,3,2,1]

Example 2:

Input: stack = [9,2,6,1,8]

Output: [8,1,6,2,9]

+ 3 hidden test cases run on Submit.

Constraints:

  • 0 ≤ stack.length ≤ 10
  • stack is given bottom-to-top (index 0 is the bottom, the last index is the top)
  • -100 ≤ stack[i] ≤ 100
  • Only push, pop, top/peek, and isEmpty are considered valid stack operations for the intended (recursive) technique — no other explicit data structure or loop may be used to reverse the contents

stack =

[1, 2, 3, 4]