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.
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.
[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>usingnamespacestd;stack<int>cloneStack(stack<int>&st){stack<int>temp,clone;// Reverse st into tempwhile(!st.empty()){temp.push(st.top());st.pop();}// Reverse temp back into clone (restores original order) and refill stwhile(!temp.empty()){intx=temp.top();temp.pop();clone.push(x);st.push(x);}returnclone;}intmain(){stack<int>st;for(intx:{1,2,3,4,5,6,7})st.push(x);stack<int>original=st;stack<int>clone=cloneStack(st);boolisValid=(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;return0;}
Java
importjava.util.*;classGfG{staticStack<Integer>cloneStack(Stack<Integer>st){Stack<Integer>temp=newStack<>();Stack<Integer>clone=newStack<>();// Reverse st into tempwhile(!st.isEmpty()){temp.push(st.pop());}// Reverse temp back into clone (restores original order) and refill stwhile(!temp.isEmpty()){intx=temp.pop();clone.push(x);st.push(x);}returnclone;}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();for(intx:newint[]{1,2,3,4,5,6,7})st.push(x);Stack<Integer>original=newStack<>();original.addAll(st);Stack<Integer>clone=cloneStack(st);booleanisValid=(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
defcloneStack(st):temp=[]clone=[]# Reverse st into tempwhilest:temp.append(st.pop())# Reverse temp back into clone (restores original order) and refill stwhiletemp:x=temp.pop()clone.append(x)st.append(x)returncloneif__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"ifis_validelse"false")
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classGfG{staticStack<int>cloneStack(Stack<int>st){Stack<int>temp=newStack<int>();Stack<int>clone=newStack<int>();// Reverse st into tempwhile(st.Count>0){temp.Push(st.Pop());}// Reverse temp back into clone (restores original order) and refill stwhile(temp.Count>0){intx=temp.Pop();clone.Push(x);st.Push(x);}returnclone;}staticvoidMain(){Stack<int>st=newStack<int>();foreach(intxinnewint[]{1,2,3,4,5,6,7})st.Push(x);int[]original=st.ToArray();Stack<int>clone=cloneStack(st);boolisValid=st.ToArray().SequenceEqual(original)&&clone.ToArray().SequenceEqual(original);Console.WriteLine(isValid?"true":"false");}}
JavaScript
functioncloneStack(st){lettemp=[];letclone=[];// Reverse st into tempwhile(st.length>0){temp.push(st.pop());}// Reverse temp back into clone (restores original order) and refill stwhile(temp.length>0){letx=temp.pop();clone.push(x);st.push(x);}returnclone;}// driver codeletst=[1,2,3,4,5,6,7];letoriginal=[...st];letclone=cloneStack(st);letisValid=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>usingnamespacestd;stack<int>cloneStack(stack<int>&st){if(st.empty()){stack<int>emptyClone;returnemptyClone;}// Remove the top element and recursively clone the remaining stackintx=st.top();st.pop();stack<int>clone=cloneStack(st);// Restore the original stack and replicate the same element in the clonest.push(x);clone.push(x);returnclone;}intmain(){stack<int>st;for(intx:{1,2,3,4,5,6,7})st.push(x);stack<int>original=st;stack<int>clone=cloneStack(st);boolisValid=(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;return0;}
Java
importjava.util.*;classGfG{staticStack<Integer>cloneStack(Stack<Integer>st){if(st.isEmpty()){returnnewStack<>();}// Remove the top element and recursively clone the remaining stackintx=st.pop();Stack<Integer>clone=cloneStack(st);// Restore the original stack and replicate the same element in the clonest.push(x);clone.push(x);returnclone;}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();for(intx:newint[]{1,2,3,4,5,6,7})st.push(x);Stack<Integer>original=newStack<>();original.addAll(st);Stack<Integer>clone=cloneStack(st);booleanisValid=(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
defcloneStack(st):ifnotst:return[]# Remove the top element and recursively clone the remaining stackx=st.pop()clone=cloneStack(st)# Restore the original stack and replicate the same element in the clonest.append(x)clone.append(x)returncloneif__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"ifis_validelse"false")
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classGfG{staticStack<int>cloneStack(Stack<int>st){if(st.Count==0){returnnewStack<int>();}// Remove the top element and recursively clone the remaining stackintx=st.Pop();Stack<int>clone=cloneStack(st);// Restore the original stack and replicate the same element in the clonest.Push(x);clone.Push(x);returnclone;}staticvoidMain(){Stack<int>st=newStack<int>();foreach(intxinnewint[]{1,2,3,4,5,6,7})st.Push(x);int[]original=st.ToArray();Stack<int>clone=cloneStack(st);boolisValid=st.ToArray().SequenceEqual(original)&&clone.ToArray().SequenceEqual(original);Console.WriteLine(isValid?"true":"false");}}
JavaScript
functioncloneStack(st){if(st.length===0){return[];}// Remove the top element and recursively clone the remaining stackletx=st.pop();letclone=cloneStack(st);// Restore the original stack and replicate the same element in the clonest.push(x);clone.push(x);returnclone;}// driver codeletst=[1,2,3,4,5,6,7];letoriginal=[...st];letclone=cloneStack(st);letisValid=JSON.stringify(st)===JSON.stringify(original)&&JSON.stringify(clone)===JSON.stringify(original);console.log(isValid?"true":"false");