14. Implement two stacks in an array
The problem can be found at the following link: Question Link
My Approach
The question is straightforward and involves implementing two stacks using the starting
and ending
of the array arr
. The main operations required are push and pop for these two stacks. Therefore, you only need to complete these functions accordingly. Additionally, the question suggests the need to handle the underflow condition of the stack.
For
push1
, we incrementtop1
and store the element at the updatedtop1
index of the array.For
push2
, we decrementtop2
and store the element at the updatedtop2
index of the array.For
pop1
, we check iftop1
is -1 (indicating an empty stack). If it is, we return -1. Otherwise, we return the element at thetop1
index and decrementtop1
.For
pop2
, we check iftop2
is equal tosize
(indicating an empty stack). If it is, we return -1. Otherwise, we return the element at thetop2
index and incrementtop2
.
The visual representation illustrates the appearance of our stacks.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity for all the operations (
push1
,push2
,pop1
,pop2
) isO(1)
because we are directly accessing the top elements and updating the pointers.Auxiliary Space Complexity:
O(1)
, Since we are not utilising any extra space.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated