Skip to main content

Reverse a Stack

Problem Statement:​

You are given a stackΒ St. You have to reverse the stack using recursion.

  • Example:

    Example 1:

    Input:
    St = {3,2,1,7,6}
    Output:
    {6,7,1,2,3}
    Explanation:
    Input stack after reversing will look like the stack in the output.
    Example 2:

    Input:
    St = {4,3,9,6}
    Output:
    {6,9,3,4}
    Explanation:
    Input stack after reversing will look like the stack in the output.


Solution:​

class Solution {
public:
// Helper to insert an element at the bottom of the stack
void InsertAtBottom(stack<int> &s, int x) {
if (s.empty()) {
s.push(x);
return;
}

int temp = s.top(); // Pop top element
s.pop();

InsertAtBottom(s, x); // Insert x at bottom recursively

s.push(temp); // Push the popped element back
}

// Main recursive function to reverse the stack
void Reverse(stack<int> &St) {
if (!St.empty()) {
int x = St.top();
St.pop();

Reverse(St); // Reverse the smaller stack
InsertAtBottom(St, x); // Insert removed element at bottom
}
}
};


βœ… How It Works​

  • Two recursive functions are used:

    1. Reverse() β€” pops all elements to the bottom
    2. InsertAtBottom() β€” puts each element back at the bottom, reversing the stack
  • Key idea:

    Pop all elements one by one

    and insert each at the bottom during backtracking


🧠 Key Points​

  • The call stack itself stores the popped elements
  • InsertAtBottom() is a helper that places an element at the bottom of the stack recursively
  • Recursive base:
    • For Reverse: stop when stack is empty
    • For InsertAtBottom: insert when stack becomes empty

⏱️ Time & Space Complexity​

MetricValue
TimeO(nΒ²) βœ…
SpaceO(n) recursion

⚠️ Edge Cases​

  • Empty stack β†’ no change
  • Single element stack β†’ remains same
  • All elements same β†’ order doesn't matter but works

πŸ’‘ Other Approaches​

ApproachTimeSpace
Recursion βœ…O(nΒ²)O(n)
Iterative (with extra stack)O(n)O(n)

  • Sort a Stack using Recursion
  • Insert element at bottom of stack
  • Design Stack with Min/Max
  • Implement Stack using Queue
πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→