![]() |
VOOZH | about |
Create a data structure twoStacks that represent two stacks. Implementation of twoStacks should use only one array, i.e., both stacks should use the same array for storing elements.
Following functions must be supported by twoStacks.
Examples:
Input: push1(2), push1(3), push2(4), pop1(), pop2(), pop2()
Output: [3, 4, -1]
Explanation: push1(2) the stack1 will be [2]
push1(3) the stack1 will be [2,3]
push2(4) the stack2 will be [4]
pop1() the popped element will be 3 from stack1 and stack1 will be [2]
pop2() the popped element will be 4 from stack2 and now stack2 is empty
pop2() the stack2 is now empty hence returned -1Input: push1(1), push2(2), pop1(), push1(3), pop1(), pop1()
Output: [1, 3, -1]
Explanation: push1(1) the stack1 will be [1]
push2(2) the stack2 will be [2]
pop1() the popped element will be 1
push1(3) the stack1 will be [3]
pop1() the popped element will be 3
pop1() the stack1 is now empty hence returned -1
Table of Content
The idea to implement two stacks is to divide the array into two halves and assign two halves to two stacks, i.e., use arr[0] to arr[n/2] for stack1, and arr[(n/2) + 1] to arr[n-1] for stack2 where arr[] is the array to be used to implement two stacks and size of array be n.
Follow the steps below to solve the problem:
To implement push1(x):
To implement push2(x):
To implement pop1():
To implement pop2():
3 4 -1
Time Complexity:
Auxiliary Space: O(n), Use of array to implement stack.
The problem with the approach is that we divide the array into two fixed halves, with one half reserved for stack1 and the other half for stack2. This can lead to inefficient space usage because if stack1 fills up, it cannot use the space available in the second half of the array for stack2, even if that space is not fully utilized.
To fix this, we should allow both stacks to grow dynamically towards each other. Instead of reserving a fixed half for each stack, stack1 will start from the left side of the array, and stack2 will start from the right side. They will grow towards each other. This way, if one stack fills up, the other stack can still use the remaining space. Overflow will only occur when both stacks meet in the middle.
The idea is to start two stacks from two extreme corners of arr[].
Follow the steps below to solve the problem:
3 4 -1
Time Complexity:
Auxiliary Space: O(n), Use of the array to implement stack.