VOOZH about

URL: https://www.geeksforgeeks.org/dsa/clone-a-stack-without-extra-space/

⇱ Clone a stack without extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Clone a stack without extra space

Last Updated : 30 May, 2026

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]


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:


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.

Comment