Clone a Stack

Last Updated : 8 Jul, 2026

Given a stack st[] of size n, return a clone of the stack without using any extra data structure for storage. The built-in copy constructor, assignment operator, or any other direct copy/clone method cannot be used.

Note: The driver code will print "true" if the returned stack is a valid clone; otherwise, it will print "false"

Example:

Input: st[] = [1, 2, 3, 4, 5, 6, 7]
Output: true
Explanation: The stack st[] is successfully cloned into another stack with the same elements in the same order.

szc

Input: st[] = [1, 1, 2, 2, 3, 3, 9]
Output: true
Explanation: The stack st[] is successfully cloned into another stack with the same elements in the same order.

Try It Yourself
redirect icon

[Naive Approach] Using an Extra Stack - O(N) Time and O(N) Space

The idea is to pop every element off the original stack and push it into a temporary stack - this reverses the order. Then pop everything from the temporary stack and push it into the clone, which reverses it back to the original order. Finally, repeat the same two-stack-reversal process to restore the original stack as well.

  • Pop 7,6,5,4,3,2,1 off st into temp : temp now holds [1,2,3,4,5,6,7] (7 at the bottom, 1 on top)
  • Pop everything from temp into clone : clone ends up as [7,6,5,4,3,2,1] (1 at the bottom, 7 on top) - same order as the original
  • Repeat the same process to refill st back to [1,2,3,4,5,6,7]
C++
#include <bits/stdc++.h>
using namespace std;

stack<int> cloneStack(stack<int>& st) {
    stack<int> temp, clone;

    // Reverse st into temp
    while (!st.empty()) {
        temp.push(st.top());
        st.pop();
    }

    // Reverse temp back into clone (restores original order) and refill st
    while (!temp.empty()) {
        int x = temp.top();
        temp.pop();
        clone.push(x);
        st.push(x);
    }
    return clone;
}

int main() {
    stack<int> st;
    for (int x : {1, 2, 3, 4, 5, 6, 7}) st.push(x);
    stack<int> original = st;

    stack<int> clone = cloneStack(st);

    bool isValid = (st.size() == original.size()) && (clone.size() == original.size());
    while (isValid && !st.empty()) {
        if (st.top() != original.top() || clone.top() != original.top()) {
            isValid = false;
            break;
        }
        st.pop();
        original.pop();
        clone.pop();
    }
    cout << (isValid ? "true" : "false") << endl;
    return 0;
}
Java
import java.util.*;

class GfG {
    static Stack<Integer> cloneStack(Stack<Integer> st) {
        Stack<Integer> temp = new Stack<>();
        Stack<Integer> clone = new Stack<>();

        // Reverse st into temp
        while (!st.isEmpty()) {
            temp.push(st.pop());
        }

        // Reverse temp back into clone (restores original order) and refill st
        while (!temp.isEmpty()) {
            int x = temp.pop();
            clone.push(x);
            st.push(x);
        }
        return clone;
    }

    public static void main(String[] args) {
        Stack<Integer> st = new Stack<>();
        for (int x : new int[]{1, 2, 3, 4, 5, 6, 7}) st.push(x);
        Stack<Integer> original = new Stack<>();
        original.addAll(st);

        Stack<Integer> clone = cloneStack(st);

        boolean isValid = (st.size() == original.size()) && (clone.size() == original.size());
        while (isValid && !st.isEmpty()) {
            if (!st.peek().equals(original.peek()) || !clone.peek().equals(original.peek())) {
                isValid = false;
                break;
            }
            st.pop();
            original.pop();
            clone.pop();
        }
        System.out.println(isValid ? "true" : "false");
    }
}
Python
def cloneStack(st):
    temp = []
    clone = []

    # Reverse st into temp
    while st:
        temp.append(st.pop())

    # Reverse temp back into clone (restores original order) and refill st
    while temp:
        x = temp.pop()
        clone.append(x)
        st.append(x)
    return clone

if __name__ == "__main__":
    st = [1, 2, 3, 4, 5, 6, 7]
    original = list(st)

    clone = cloneStack(st)

    is_valid = (st == original) and (clone == original)
    print("true" if is_valid else "false")
C#
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {
    static Stack<int> cloneStack(Stack<int> st) {
        Stack<int> temp = new Stack<int>();
        Stack<int> clone = new Stack<int>();

        // Reverse st into temp
        while (st.Count > 0) {
            temp.Push(st.Pop());
        }

        // Reverse temp back into clone (restores original order) and refill st
        while (temp.Count > 0) {
            int x = temp.Pop();
            clone.Push(x);
            st.Push(x);
        }
        return clone;
    }

    static void Main() {
        Stack<int> st = new Stack<int>();
        foreach (int x in new int[] { 1, 2, 3, 4, 5, 6, 7 }) st.Push(x);
        int[] original = st.ToArray();

        Stack<int> clone = cloneStack(st);

        bool isValid = st.ToArray().SequenceEqual(original) && clone.ToArray().SequenceEqual(original);
        Console.WriteLine(isValid ? "true" : "false");
    }
}
JavaScript
function cloneStack(st) {
    let temp = [];
    let clone = [];

    // Reverse st into temp
    while (st.length > 0) {
        temp.push(st.pop());
    }

    // Reverse temp back into clone (restores original order) and refill st
    while (temp.length > 0) {
        let x = temp.pop();
        clone.push(x);
        st.push(x);
    }
    return clone;
}

// driver code
let st = [1, 2, 3, 4, 5, 6, 7];
let original = [...st];

let clone = cloneStack(st);

let isValid = JSON.stringify(st) === JSON.stringify(original) &&
              JSON.stringify(clone) === JSON.stringify(original);
console.log(isValid ? "true" : "false");

Output
true

[Expected Approach] Using Recursion - O(N) Time and O(N)(Recursion) Space

The idea is to remove the top element, recursively clone whatever remains, and then - on the way back up as the recursion unwinds - push that same element onto both the original stack (to restore it) and the new clone (to build it).

Since the unwind happens in reverse order of the pops, everything ends up back in its original order on both stacks, with no second data structure ever explicitly created.

  • Pop 7 off st, recurse on the rest [1,2,3,4,5,6]
  • Continue popping down to 1, then to an empty stack - base case returns an empty clone
  • Unwinding back up: push 1 onto both st and clone, then 2, then 3, ..., finally 7
  • Both st and clone end up holding [1,2,3,4,5,6,7], in the same order
C++
#include <bits/stdc++.h>
using namespace std;

stack<int> cloneStack(stack<int>& st) {
    if (st.empty()) {
        stack<int> emptyClone;
        return emptyClone;
    }

    // Remove the top element and recursively clone the remaining stack
    int x = st.top();
    st.pop();
    stack<int> clone = cloneStack(st);

    // Restore the original stack and replicate the same element in the clone
    st.push(x);
    clone.push(x);
    return clone;
}

int main() {
    stack<int> st;
    for (int x : {1, 2, 3, 4, 5, 6, 7}) st.push(x);
    stack<int> original = st;

    stack<int> clone = cloneStack(st);

    bool isValid = (st.size() == original.size()) && (clone.size() == original.size());
    while (isValid && !st.empty()) {
        if (st.top() != original.top() || clone.top() != original.top()) {
            isValid = false;
            break;
        }
        st.pop();
        original.pop();
        clone.pop();
    }
    cout << (isValid ? "true" : "false") << endl;
    return 0;
}
Java
import java.util.*;

class GfG {
    static Stack<Integer> cloneStack(Stack<Integer> st) {
        if (st.isEmpty()) {
            return new Stack<>();
        }

        // Remove the top element and recursively clone the remaining stack
        int x = st.pop();
        Stack<Integer> clone = cloneStack(st);

        // Restore the original stack and replicate the same element in the clone
        st.push(x);
        clone.push(x);
        return clone;
    }

    public static void main(String[] args) {
        Stack<Integer> st = new Stack<>();
        for (int x : new int[]{1, 2, 3, 4, 5, 6, 7}) st.push(x);
        Stack<Integer> original = new Stack<>();
        original.addAll(st);

        Stack<Integer> clone = cloneStack(st);

        boolean isValid = (st.size() == original.size()) && (clone.size() == original.size());
        while (isValid && !st.isEmpty()) {
            if (!st.peek().equals(original.peek()) || !clone.peek().equals(original.peek())) {
                isValid = false;
                break;
            }
            st.pop();
            original.pop();
            clone.pop();
        }
        System.out.println(isValid ? "true" : "false");
    }
}
Python
def cloneStack(st):
    if not st:
        return []

    # Remove the top element and recursively clone the remaining stack
    x = st.pop()
    clone = cloneStack(st)

    # Restore the original stack and replicate the same element in the clone
    st.append(x)
    clone.append(x)
    return clone

if __name__ == "__main__":
    st = [1, 2, 3, 4, 5, 6, 7]
    original = list(st)

    clone = cloneStack(st)

    is_valid = (st == original) and (clone == original)
    print("true" if is_valid else "false")
C#
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {
    static Stack<int> cloneStack(Stack<int> st) {
        if (st.Count == 0) {
            return new Stack<int>();
        }

        // Remove the top element and recursively clone the remaining stack
        int x = st.Pop();
        Stack<int> clone = cloneStack(st);

        // Restore the original stack and replicate the same element in the clone
        st.Push(x);
        clone.Push(x);
        return clone;
    }

    static void Main() {
        Stack<int> st = new Stack<int>();
        foreach (int x in new int[] { 1, 2, 3, 4, 5, 6, 7 }) st.Push(x);
        int[] original = st.ToArray();

        Stack<int> clone = cloneStack(st);

        bool isValid = st.ToArray().SequenceEqual(original) && clone.ToArray().SequenceEqual(original);
        Console.WriteLine(isValid ? "true" : "false");
    }
}
JavaScript
function cloneStack(st) {
    if (st.length === 0) {
        return [];
    }

    // Remove the top element and recursively clone the remaining stack
    let x = st.pop();
    let clone = cloneStack(st);

    // Restore the original stack and replicate the same element in the clone
    st.push(x);
    clone.push(x);
    return clone;
}

// driver code
let st = [1, 2, 3, 4, 5, 6, 7];
let original = [...st];

let clone = cloneStack(st);

let isValid = JSON.stringify(st) === JSON.stringify(original) &&
              JSON.stringify(clone) === JSON.stringify(original);
console.log(isValid ? "true" : "false");

Output
true
Comment