Open In App

Clone a stack without extra space

Last Updated : 20 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a source stack, copy the contents of the source stack to the destination stack maintaining the same order without using extra space.

Examples: 

Input: st = [ 3, 2, 1 ]
Output: Clone : [3, 2, 1]

Input: st = [10, 5, 4]
Output: Clone = [10, 5, 4]

Reverse The Stack - O(n ^ 2) Time and O(1) Space

The idea is to reverse the given stack using cloned stack as auxiliary. To reverse the stack, we mainly one by one move the top of the given stack to the bottom.

[1, 2. 3. 4] => [4, 1, 2, 3] => [4, 3, 1, 2] => [4, 3, 2, 1]

After this step, our task is simple, we only need to move the items one by one to clone and our clone becomes [1, 2, 3, 4]

C++
#include <bits/stdc++.h>
using namespace std;

void clonedStack(stack<int> &st, stack<int> &cloned) {

    int count = 0;

    // reverse the order of the values in source stack
    while(count != st.size() - 1) {
        int topVal = st.top();
        st.pop();
        while(count != st.size()) {
            cloned.push(st.top());
            st.pop();
        }
        st.push(topVal);
        while(cloned.size() != 0) {
            st.push(cloned.top());
            cloned.pop();
        }
        count += 1;
    }

    // pop the values from source and
    // push into destination stack
    while(st.size() != 0) {
        cloned.push(st.top());
        st.pop();
    }
}

int main() {
    stack<int> source, dest;
    source.push(1);
    source.push(2);
    source.push(3);

    cout << "Source Stack:" << endl;
    stack<int> temp = source;
    while(!temp.empty()) {
        cout << temp.top() << " ";
        temp.pop();
    }
    cout << endl;

    clonedStack(source, dest);

    cout << "Destination Stack:" << endl;
    while(!dest.empty()) {
        cout << dest.top() << " ";
        dest.pop();
    }

    return 0;
}
Java
import java.util.*;

class GfG {

    static void clonedStack(Stack<Integer> st, Stack<Integer> cloned) {

        int count = 0;

        // reverse the order of the values in source stack
        while(count != st.size() - 1) {
            int topVal = st.peek();
            st.pop();
            while(count != st.size()) {
                cloned.push(st.peek());
                st.pop();
            }
            st.push(topVal);
            while(cloned.size() != 0) {
                st.push(cloned.peek());
                cloned.pop();
            }
            count += 1;
        }

        // pop the values from source and
        // push into destination stack
        while(st.size() != 0) {
            cloned.push(st.peek());
            st.pop();
        }
    }

    public static void main(String[] args) {
        Stack<Integer> source = new Stack<>();
        Stack<Integer> dest = new Stack<>();
        source.push(1);
        source.push(2);
        source.push(3);

        System.out.println("Source Stack:");
        Stack<Integer> temp = (Stack<Integer>) source.clone();
        while(!temp.empty()) {
            System.out.print(temp.peek() + " ");
            temp.pop();
        }
        System.out.println();

        clonedStack(source, dest);

        System.out.println("Destination Stack:");
        while(!dest.empty()) {
            System.out.print(dest.peek() + " ");
            dest.pop();
        }
    }
}
Python
def clonedStack(st, cloned):

    count = 0

    # reverse the order of the values in source stack
    while count != len(st) - 1:
        topVal = st[-1]
        st.pop()
        while count != len(st):
            cloned.append(st[-1])
            st.pop()
        st.append(topVal)
        while len(cloned) != 0:
            st.append(cloned[-1])
            cloned.pop()
        count += 1

    # pop the values from source and
    # push into destination stack
    while len(st) != 0:
        cloned.append(st[-1])
        st.pop()


source = []
dest = []
source.append(1)
source.append(2)
source.append(3)

print("Source Stack:")
temp = source[:]
while temp:
    print(temp[-1], end=" ")
    temp.pop()
print()

clonedStack(source, dest)

print("Destination Stack:")
while dest:
    print(dest[-1], end=" ")
    dest.pop()
C#
using System;
using System.Collections.Generic;

class GfG {

    static void clonedStack(Stack<int> st, Stack<int> cloned) {

        int count = 0;

        // reverse the order of the values in source stack
        while(count != st.Count - 1) {
            int topVal = st.Peek();
            st.Pop();
            while(count != st.Count) {
                cloned.Push(st.Peek());
                st.Pop();
            }
            st.Push(topVal);
            while(cloned.Count != 0) {
                st.Push(cloned.Peek());
                cloned.Pop();
            }
            count += 1;
        }

        // pop the values from source and
        // push into destination stack
        while(st.Count != 0) {
            cloned.Push(st.Peek());
            st.Pop();
        }
    }

    static void Main() {
        Stack<int> source = new Stack<int>();
        Stack<int> dest = new Stack<int>();
        source.Push(1);
        source.Push(2);
        source.Push(3);

        Console.WriteLine("Source Stack:");
        Stack<int> temp = new Stack<int>(new Stack<int>(source));
        while(temp.Count != 0) {
            Console.Write(temp.Peek() + " ");
            temp.Pop();
        }
        Console.WriteLine();

        clonedStack(source, dest);

        Console.WriteLine("Destination Stack:");
        while(dest.Count != 0) {
            Console.Write(dest.Peek() + " ");
            dest.Pop();
        }
    }
}
JavaScript
function clonedStack(st, cloned) {

    let count = 0;

    // reverse the order of the values in source stack
    while(count !== st.length - 1) {
        let topVal = st[st.length - 1];
        st.pop();
        while(count !== st.length) {
            cloned.push(st[st.length - 1]);
            st.pop();
        }
        st.push(topVal);
        while(cloned.length !== 0) {
            st.push(cloned[cloned.length - 1]);
            cloned.pop();
        }
        count += 1;
    }

    // pop the values from source and
    // push into destination stack
    while(st.length !== 0) {
        cloned.push(st[st.length - 1]);
        st.pop();
    }
}

let source = [];
let dest = [];
source.push(1);
source.push(2);
source.push(3);

console.log("Source Stack:");
let temp = [...source];
while(temp.length) {
    console.log(temp[temp.length - 1] + " ");
    temp.pop();
}

clonedStack(source, dest);

console.log("Destination Stack:");
while(dest.length) {
    console.log(dest[dest.length - 1] + " ");
    dest.pop();
}

Output
Source Stack:
3 2 1 
Destination Stack:
3 2 1 

Using Recursion - O(n) Time and O(n) Space for Recursion Call Stack

The idea is to use recursion to reverse the source stack and then build the cloned stack as we return from the recursive calls. This eliminates the need for explicit iteration or auxiliary data structures to track the order. We recursively pop each element from the source stack until it becomes empty. Then, as the recursive calls unwind, we push those elements into the cloned stack in the original bottom-to-top order, effectively cloning the stack.

Follow the below given steps:

  • Pass two stack references: one for the original stack and another for the cloned stack.
  • If the original stack is empty, return (base case for recursion).
  • Pop the top element from the original stack and store it in a temporary variable.
  • Make a recursive call with the modified original stack and the cloned stack.
  • After the recursive call returns, push the temporarily stored element into the cloned stack.

Below is given the implementation:

C++
#include <bits/stdc++.h>
using namespace std;

void clonedStack(stack<int> &st, stack<int> &cloned) {

    // If the source stack is empty, return.
    if (st.empty())
        return;

    // Pop an element from the source stack.
    int temp = st.top();
    st.pop();

    // Recursively clone the remaining elements.
    clonedStack(st, cloned);

    // Push the popped element to the cloned stack.
    cloned.push(temp);
}

int main() {
    stack<int> source, dest;
    source.push(1);
    source.push(2);
    source.push(3);

    cout << "Source Stack:" << endl;
    stack<int> temp = source;
    while(!temp.empty()) {
        cout << temp.top() << " ";
        temp.pop();
    }
    cout << endl;

    clonedStack(source, dest);

    cout << "Destination Stack:" << endl;
    while(!dest.empty()) {
        cout << dest.top() << " ";
        dest.pop();
    }

    return 0;
}
Java
import java.util.*;

class GfG {

    static void clonedStack(Stack<Integer> st, Stack<Integer> cloned) {

        // If the source stack is empty, return.
        if (st.empty())
            return;

        // Pop an element from the source stack.
        int temp = st.peek();
        st.pop();

        // Recursively clone the remaining elements.
        clonedStack(st, cloned);

        // Push the popped element to the cloned stack.
        cloned.push(temp);
    }

    public static void main(String[] args) {
        Stack<Integer> source = new Stack<>();
        Stack<Integer> dest = new Stack<>();
        source.push(1);
        source.push(2);
        source.push(3);

        System.out.println("Source Stack:");
        Stack<Integer> temp = (Stack<Integer>) source.clone();
        while(!temp.empty()) {
            System.out.print(temp.peek() + " ");
            temp.pop();
        }
        System.out.println();

        clonedStack(source, dest);

        System.out.println("Destination Stack:");
        while(!dest.empty()) {
            System.out.print(dest.peek() + " ");
            dest.pop();
        }
    }
}
Python
def clonedStack(st, cloned):

    # If the source stack is empty, return.
    if not st:
        return

    # Pop an element from the source stack.
    temp = st[-1]
    st.pop()

    # Recursively clone the remaining elements.
    clonedStack(st, cloned)

    # Push the popped element to the cloned stack.
    cloned.append(temp)


source = []
dest = []
source.append(1)
source.append(2)
source.append(3)

print("Source Stack:")
temp = source.copy()
while temp:
    print(temp[-1], end=" ")
    temp.pop()
print()

clonedStack(source, dest)

print("Destination Stack:")
while dest:
    print(dest[-1], end=" ")
    dest.pop()
C#
using System;
using System.Collections.Generic;

class GfG {

    static void clonedStack(Stack<int> st, Stack<int> cloned) {

        // If the source stack is empty, return.
        if (st.Count == 0)
            return;

        // Pop an element from the source stack.
        int temp = st.Peek();
        st.Pop();

        // Recursively clone the remaining elements.
        clonedStack(st, cloned);

        // Push the popped element to the cloned stack.
        cloned.Push(temp);
    }

    static void Main() {
        Stack<int> source = new Stack<int>();
        Stack<int> dest = new Stack<int>();
        source.Push(1);
        source.Push(2);
        source.Push(3);

        Console.WriteLine("Source Stack:");
        Stack<int> temp = new Stack<int>(new Stack<int>(source));
        while(temp.Count > 0) {
            Console.Write(temp.Peek() + " ");
            temp.Pop();
        }
        Console.WriteLine();

        clonedStack(source, dest);

        Console.WriteLine("Destination Stack:");
        while(dest.Count > 0) {
            Console.Write(dest.Peek() + " ");
            dest.Pop();
        }
    }
}
JavaScript
function clonedStack(st, cloned) {

    // If the source stack is empty, return.
    if (st.length === 0)
        return;

    // Pop an element from the source stack.
    let temp = st[st.length - 1];
    st.pop();

    // Recursively clone the remaining elements.
    clonedStack(st, cloned);

    // Push the popped element to the cloned stack.
    cloned.push(temp);
}

let source = [];
let dest = [];
source.push(1);
source.push(2);
source.push(3);

console.log("Source Stack:");
let temp = [...source];
while (temp.length !== 0) {
    console.log(temp[temp.length - 1] + " ");
    temp.pop();
}

clonedStack(source, dest);

console.log("Destination Stack:");
while (dest.length !== 0) {
    console.log(dest[dest.length - 1] + " ");
    dest.pop();
}

Output
Source Stack:
3 2 1 
Destination Stack:
3 2 1 

Note: This solution does not use any explicit space but requires function call stack space to manage recursion.


Next Article

Similar Reads