![]() |
VOOZH | about |
Given a stack and an element, our task is to insert the element at the bottom of the stack in JavaScript.
Example:
Input:
Initial Stack: [1, 2, 3, 4]
N= 5
Output:
Final Stack: [5, 1, 2, 3, 4]
Below are the approaches to inserting an element at the bottom of the stack:
Table of Content
In this approach, we initialize a temporary stack. We will pop all elements from the original stack and push all of them into the temporary stack and also we will push the new element to the temporary stack. Now one by one we will pop all elements from the temporary stack and push them to the original stack.
Example: In this example, we use an additional stack to insert an element at the bottom of the stack.
Stack before insertion: [ 4, 6, 8, 10 ] Stack after insertion: [ 2, 4, 6, 8, 10 ]
Time Complexity: O(N)
Auxiliary Space: O(N)
In this approach, we use a recursive approach to insert an element at the bottom of the stack. We will recursively pop all elements from the stack we insert the new element at the bottom and then push back all the elements. Now the new element will be at the bottom.
Example: In this example, we use a recursive approach to insert an element at the bottom of the stack.
Stack before insertion: [ 6, 9, 12, 15 ] Stack after insertion: [ 3, 6, 9, 12, 15 ]
Time Complexity: O(N)
Auxiliary Space: O(N)