Challenge: Implement Two Stacks using One Array

Can you implement two stacks using a single array? A solution is placed in the "solution" section for your help, but we would suggest you solve it on your own first.

Problem Statement

Write code for the following functions to implement two stacks using a single array of a fixed size to store the elements.

Function Prototypes

push1(value)
push2(value):
pop1():
pop2():

Input/Output

push1(value)

Input: an integer

Output: inserts the given value in the first stack, i.e., stack1

push2(value)

Input: an integer

Output: inserts the given value in the second stack i.e., stack2

pop1()

Output: returns and remove the top value of stack1

pop2()

Output: returns and remove the top value of stack2

Note: s is the maximum size that the array can have, and it is passed to the constructor of the class twoStacks.

See the illustration for your understanding:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.