


Note: If a pop operation is used in an empty stack nothing happens to the stack, but you have to print -1.
The first line of the input contains ‘T’ denoting the number of test cases.
The first line of each test case contains ‘Q’ denoting the number of queries.
In the next Q lines input is either of the types :
Id 0: where ‘id’ is the index of the stack ( out of the three ) in which we have to work on, 0 means we have to pop a top element from the stack.
Id 1 ele: where ‘id’ is the index of the stack ( out of the three ) in which we have to work on, 1 means we have to push ‘ele’ element on top of the stack.
For each query of type 0, If the stack is non-empty print the removed element.
If a stack is empty print -1.
Print each element in the new line.
1 <= T <= 3
0 <= Q, ele <= 10^5
0 <= id <= 2 , denoting one of the three stack
Time Limit : 1 sec
You will create an array ‘arr’ of size Q which will keep all the elements pushed in three arrays. Since we are using 3 stacks in a single array, we need to have a way of finding the position of the top of the stack (tos) in the array, for which we will store the tos position of all 3 stacks. You also need an array ‘prev’ of size Q, where prev[i] tells what is the index of the prev element in the current stack.
Eg: if the input is
1
7
0 1 5
0 1 1
1 1 6
2 1 8
0 1 4
1 1 2
0 1 6
Then our arrays will be like this:
tos= {6 , 4, 3} , // tos stores position of top of stack
Prev[1] =0, because in stack 0 if we pop the element at position 1, the tos will be 5 which is at position 0.
Algo for pop operation:
tos[stack_id]= prev[ tos[ stack_id ] ].
Algo for push operation:
The approach is mostly the same as brute force, the only difference is instead of doing findEmptyIndex() in O(Q), we will do it in O( log(Q) ) using set or priority queue.
Or we can also do it in O(1) using unordered_set