← OYO questions
CodingReported in a candidate post, Aug 2019

Reverse a stack using recursion

Filed under OYO · Also reported at Citrix, Providence Global Centre

Free read 3 of 3

Use two recursive functions: one to hold elements off the stack, and a helper `insert_at_bottom`.

The question

Given a stack of integers, reverse the stack in-place using only recursion. You must not use any loops (`for`, `while`) or additional data structures (like arrays, queues, or another stack).

Constraints

  • 0 <= stack.length <= 10^3
  • -10^9 <= element <= 10^9

Examples

Input
stack = [1, 2, 3, 4]
Output
[4, 3, 2, 1]
Why
Top of stack changes from 4 to 1, effectively reversing element order.

Approach

  1. Use two recursive functions: one to hold elements off the stack, and a helper `insert_at_bottom`.

Solution

O(n^2) time, O(n) space (call stack)

Python
class Solution:
    def insert_at_bottom(self, stack: list[int], item: int) -> None:
        if not stack:
            stack.append(item)
            return
        top = stack.pop()
        self.insert_at_bottom(stack, item)
        stack.append(top)

    def reverse_stack(self, stack: list[int]) -> None:
        if not stack:
            return
        top = stack.pop()
        self.reverse_stack(stack)
        self.insert_at_bottom(stack, top)

Tips

  • What they are testing: Tests mastery of recursion and call stack frames as implicit auxiliary storage.
  • Common mistake: Attempting to reverse using a single recursive function rather than a helper that inserts at the bottom.

Related OYO questions

Collected from public candidate posts and coding forums. Updated Nov 2026.