Challenge 2: Implement Two Stacks Using One Array

Can you implement two stacks using a single array?

Problem statement

Implement the following functions to implement two stacks by using a single array to store elements. You can make changes to the constructor as well. A solution is placed in the solution section for your help, but it is suggested that you solve it on your own first.

Function prototypes

void push1(int value):
void push2(int value):
void pop1():
void 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 removes the top value of stack1.

pop2()

Output: Returns and removes the top value of stack2.

See the illustration for your understanding:

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