24(March) Insert an Element at the Bottom of a Stack

24. Insert an Element at the Bottom of a Stack

The problem can be found at the following link: Question Link

Problem Description

You are given a stack st of (n) integers and an element (x). You have to insert (x) at the bottom of the given stack.

Example:

Input:

n = 5
x = 2
st = {4,3,2,1,8}

Output:

{2,4,3,2,1,8}

Explanation: After insertion of 2, the final stack will be {2,4,3,2,1,8}.

My Approach

  1. Insertion Process:

    • Create a temporary stack tmp.

    • Push all elements from the original stack st to the temporary stack tmp.

    • Push the new element (x) to the bottom of the stack st.

    • Push back all elements from the temporary stack tmp to the original stack st.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where (n) is the number of elements in the stack.

  • Expected Auxiliary Space Complexity: O(n), as we use a temporary stack to store the elements.

Code (C++)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated