Clone a stack without extra space
Last Updated :
20 Apr, 2025
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();
}
OutputSource 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();
}
OutputSource 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.
Similar Reads
Clone a stack without using extra space | Set 2
Given a stack S, the task is to copy the content of the given stack S to another stack T maintaining the same order.Examples:Input: Source:- |5| |4| |3| |2| |1|Output: Destination:- |5| |4| |3| |2| |1|Input: Source:- |12| |13| |14| |15| |16|Output: Destination:- |12| |13| |14| |15| |16|Reversing the
7 min read
Reverse a stack without using extra space in O(n)
Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed. Examples: Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6 We have discussed a way of reversing a stack in the below post.Reverse a Stack using Recu
6 min read
Check if the two given stacks are same
Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: Approach: Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or
6 min read
How to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop.Example: Input: elements present in stack from top to bottom 4 3 2 1Output: 1 2 3 4Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1The idea of the solution is to hold all values in Function Call Stack un
4 min read
Merge two BSTs with limited extra space
Given two Binary Search Trees(BST), print the inorder traversal of merged BSTs. Examples: Input: First BST 3 / \ 1 5Second BST 4 / \2 6Output: 1 2 3 4 5 6 Input:First BST 8 / \ 2 10 / 1Second BST 5 / 3 /0Output: 0 1 2 3 5 8 10 Recommended PracticeMerge two BST 'sTry It!Merge two BSTs using Iterative
15+ min read
Reversing a Stack using two empty Stacks
Given a stack S, the task is to reverse the stack S using two additional stacks. Example: Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1âtop2345After reversing it, use two additional stacks:5âtop4321 Input: S={1, 25, 17}Output: 17 25 1 Approach: Follow the steps below to
6 min read
How to create mergeable stack?
Design a stack with the following operations. push(Stack s, x): Adds an item x to stack s pop(Stack s): Removes the top item from stack s merge(Stack s1, Stack s2): Merge contents of s2 into s1. Time Complexity of all above operations should be O(1). If we use array implementation of the stack, then
8 min read
C++ Program to Implement Stack using array
Stack is the fundamental data structure that can operates the under the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Implementing the stack using the array is one of the most straightforward methods in the terms of the both
4 min read
Python program to reverse a stack
The stack is a linear data structure which works on the LIFO concept. LIFO stands for last in first out. In the stack, the insertion and deletion are possible at one end the end is called the top of the stack. In this article, we will see how to reverse a stack using Python. Algorithm: Define some b
3 min read
Sudo Placement[1.3] | Playing with Stacks
You are given 3 stacks, A(Input Stack), B(Auxiliary Stack) and C(Output Stack). Initially stack A contains numbers from 1 to N, you need to transfer all the numbers from stack A to stack C in sorted order i.e in the end, the stack C should have smallest element at the bottom and largest at top. You
7 min read