Challenge: Implement Two Stacks Using One List

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 to solve it on your own first.

Problem Statement

Implement the following functions to implement two stacks using a single array such that for storing elements both stacks should use the same array. An illustration is also provided for your understanding. Also, for this problem, initialize a Python list with the provided fixed size and perform all the operations in-place without growing or shrinking the list!

Function Prototypes

def push1(value): # pushes value in stack 1
def push2(value): # pushes value in stack 2
def pop1(): # pops an element from stack 1 
def pop2():# pops an element from stack 2 

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

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