Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Reverse Stack Using Recursion

Easy
0/40
Average time to solve is 21m
profile
Contributed by
353 upvotes
Asked in companies
AmazonOracleRazorpay

Problem statement

Reverse a given stack of 'N' integers using recursion. You are required to make changes in the input parameter itself.


Note: You are not allowed to use any extra space other than the internal stack space used due to recursion.


Example:
Input: [1,2,3,4,5] 
Output: [5,4,3,2,1]

add image

Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of input contains an integer value 'N', denoting the size of the input Stack.

The second line contains 'N' single space-separated integers, denoting the stack elements, where the leftmost integer denotes the TOP element of Stack.    
Output Format :
'N' single space-separated integers in a single line, where the leftmost integer denotes the TOP element of the reversed stack.
Sample Input 1 :
3
2 1 3
Sample Output 1 :
3 1 2
Explanation to Sample Input 1 :
Reverse of a give stack is 3 1 2 where first element becomes last and last becomes first.                   
Sample Input 2 :
2
3 2
Sample Output 2 :
2 3
Constraints :
0 <= N <= 10^3
Where 'N' is the number of elements in the given stack.

Time Limit: 1 sec
Hint

Use the recursion call stack to store the elements of the stack and reverse it.

Approaches (1)
Recursive Approach

We will be using two recursive methods:

  1. To Reverse the Stack: We will use recursion to iterate through the stack. For each top element, we will pop it and use recursion to reverse the remaining stack. After getting the stack reversed by recursion we can simply push the popped element to the bottom of the stack. The procedure to push the element at the bottom of stack is explained in following paragraph.
  2. To Push an element to the Bottom of Stack: For this, we will be using recursion. Now to push a given element to the bottom of the stack, we will iterate through the stack recursively. For each top element, we will pop it and call recursion to insert a given element at the bottom of the remaining stack. After recursive function does its work and adds the given element to the bottom of stack, then we can simply push the popped element to the top of the stack.

Algorithm: 

  1. ReverseStack(stack)
    1. If the stack is empty, then return
    2. Pop the top element from the stack as top
    3. Reverse the remaining elements in the stack, call reverseStack(stack) method
    4. Insert the top element to the bottom of the stack, call InsertAtBottom(stack, top) method
  2. InsertAtBottom(stack, ele)
    1. If the stack is empty, push ele to stack, return
    2. Pop the top element from the stack as top
    3. Insert the ele to the bottom of the stack, call InsertAtBottom(stack, ele) method
    4. Push top to the stack.
Time Complexity

O(N^2), where ‘N’ is the total number of elements in the given stack.

 

In the worst case, reverseStack method will be called for each element in the stack( requires O(N)) time, and for each call of the reverse stack, we call InsertAtBottom which also takes O(N) time.

Space Complexity

O(N), where ‘N’ is the total number of elements in the given stack.

 

In the worst case, the depth of recursion can extend up to O(N). So, extra space will be required for the recursion stack.

Code Solution
(100% EXP penalty)
Reverse Stack Using Recursion
All tags
Sort by
Search icon

Interview problems

C++ solution 100% cleared

void insertAtBottom(stack<int> &s, int element) {

    if(s.empty()) {
        s.push(element);
        return;
    }

    int num = s.top();
    s.pop();

    insertAtBottom(s, element);

    s.push(num);
}

void reverseStack(stack<int> &stack) {
    if(stack.empty()) {
        return;
    }

    int num = stack.top();
    stack.pop();
    
    reverseStack(stack);

    insertAtBottom(stack, num);
}
14 views
0 replies
0 upvotes

Interview problems

easy to understand

#include <stack>

using namespace std;

 

void insertAtBottom(stack<int> &s, int ele) {

if (s.empty()) {

s.push(ele);

} else {

int top = s.top();

s.pop();

insertAtBottom(s, ele);

s.push(top);

}

return;

}

 

void reverseStack(stack<int> &s) {

if (s.empty()) {

return;

}

int top = s.top();

s.pop();

reverseStack(s);

insertAtBottom(s, top);

}

 

137 views
0 replies
0 upvotes

Interview problems

"Reverse Stack Using Recursion" using C++

void insertSort(stack<int> &stack, int temp){

    if(stack.empty()){

        stack.push(temp);

        return;

    } 

    int var = stack.top();

    stack.pop();

    insertSort(stack, temp);

    stack.push(var);

}

 

void reverseStack(stack<int> &stack) {

    // Write your code here

    if(stack.empty()) return;

 

    int temp = stack.top();

    stack.pop();

    reverseStack(stack);

    insertSort(stack, temp);

}

100 views
0 replies
0 upvotes

Interview problems

Using recursion

void insertBottom(stack<int> &stack, int ele){

    //base case

    if(stack.empty()){

        stack.push(ele);

        return;

    }

 

    int val = stack.top();

    stack.pop();

    insertBottom(stack, ele);

    stack.push(val);

}

void reverseStack(stack<int> &stack) {

    //base case

    if(stack.empty()){

        return;

    }

 

    int val = stack.top();

    stack.pop();

    reverseStack(stack);

 

    insertBottom(stack, val);

}

198 views
0 replies
0 upvotes

Interview problems

easy solution

void insert_at_bottom(stack<int>&st,int ele)

{

    

     if(st.empty())

    {

        st.push(ele);

        return;

    }

    

    int topele=st.top();

    st.pop();

    

   

    insert_at_bottom(st,ele);

    st.push(topele);

    

}

 

void reverseStack(stack<int>&s)

{

    if(s.empty())

    {

        return;

    }

    

    int ele=s.top();

    s.pop();

    

    reverseStack(s);

    

    insert_at_bottom(s,ele);

    

}

 

87 views
0 replies
0 upvotes

Interview problems

Reverse Stack Using Recursion 🔥

// Function to insert an element at the bottom of the stack 📦
void insertStack(stack<int>& stack, int x) {
   // Base case: if the stack is empty, just push the element 🤔
   if (stack.empty()) { 
       stack.push(x);  // Stack: [x] 👍
       return;
   }
   // Store the top element and pop it from the stack 💸
   int num = stack.top();  // num = top element 👀
   stack.pop();            // Remove the top element 🔥
   // Recursive call to insert the element at the bottom 🔄
   insertStack(stack, x);  // Insert x at the bottom 🔩
   // Push the stored top element back into the stack 💪
   stack.push(num);        // Stack: [..., x, num] 👍
}
// Function to reverse the stack 🔙
void reverseStack(stack<int>& stack) {
   // Base case: if the stack is empty, do nothing 🙅‍♂️
   if (stack.empty()) {
       return;
   }
   // Store the top element and pop it from the stack 💸
   int top = stack.top();  // top = top element 👀
   stack.pop();            // Remove the top element 🔥
   // Recursive call to reverse the remaining stack 🔄
   reverseStack(stack);    // Reverse the remaining stack 🔙
   // Insert the stored top element at the bottom of the stack 📦
   insertStack(stack, top); // Insert top at the bottom 🔩
}

 

 

// Example usage: 

// Take stack: [1, 2] 📈 

// 1. top = 2 👀 

// then remove the 2 from the top 🔥 

// and make a recursive call 🔄 

// now top = 1 👀 

// again remove the top 🔥 

// now stack becomes empty 📦 

 

// Now make a recursive call to insertStack to insert element 📦 

// Stack: [] 📦 

// Stack: [1] 👍 and return 

// Again make a call and now stack: [1] 📈 

// top = 1 👀 

// In next iteration if Stack: [1] 🤔 

// pop the top element to insert new element 🔥 

// Now 1 is pop and stack becomes empty 📦 

// element 2 is push into stack 🔩 

// and then 1 is push into stack 👍 

// Stack becomes [2, 1] 📈

80 views
0 replies
0 upvotes

Interview problems

easy soln || recursive approach || c++ soln

void solve(stack<int>& s,int x){

    //base case

    if(s.empty()){

        s.push(x);

        return ;

    }

     int num=s.top();

    s.pop();

 

    //recursive call

    solve(s,x);

 

    s.push(num);

}

 

void reverseStack(stack<int> &stack) {

    //base case

    if(stack.empty()){

        return ;

    }

 

    int num=stack.top();

    stack.pop();

 

    //recursive call

    reverseStack(stack);

 

    solve(stack,num);

}

95 views
0 replies
1 upvote

Interview problems

Easy java solution using extra space

import java.util.Stack;

 

public class Solution {

 

public static void reverseStack(Stack<Integer> stack) {

// write your code here

Stack<Integer> stack1 = new Stack<>();

Stack<Integer> stack2 = new Stack<>();

 

while(!stack.isEmpty()){

stack1.push(stack.pop());

}

 

while(!stack1.isEmpty()){

stack2.push(stack1.pop());

}

 

while(!stack2.isEmpty()){

stack.push(stack2.pop());

}

 

 

 

 

}

 

}

 

89 views
0 replies
0 upvotes

Interview problems

C++ Code || Using recursion

void insertAtBottom(stack<int>& stack, int x ){

    // base case

    if(stack.empty()){

        stack.push(x);

        return;

    }

 

    int num = stack.top();

    stack.pop();

 

    // recursive call

    insertAtBottom(stack,x);

    stack.push(num);

}

 

void reverseStack(stack<int> &stack) {

    // base case 

    if(stack.empty()){

        return ;

    }

 

    int num = stack.top();

    stack.pop();

 

    // recursive call

    reverseStack(stack);

 

    insertAtBottom(stack,num);

}

93 views
0 replies
2 upvotes

Interview problems

Easy Solution Using Cpp

void insertAtBottom(stack<int>& myStack, int x){

    if(myStack.empty()){
        myStack.push(x);
        return;
    }
    int num = myStack.top();
    myStack.pop();
    insertAtBottom(myStack,x);
    myStack.push(num);
}
void reverseStack(stack<int> &stack) {
    if(stack.empty()){
        return;
    }

    int num = stack.top();
    stack.pop();
    reverseStack(stack);
    insertAtBottom(stack,num);
}
112 views
0 replies
0 upvotes
Full screen
Console