Implement Three Stacks Using a Single Array

You are given a sequence of queries for insertion and deletion operations on 3 separate stacks. Your task is to implement these three stacks using a single array while ensuring that the array's size does not exceed the total number of queries.

Input Format:

The first line of the input contains a single integer 'T', indicating the number of test cases. Each test case begins with an integer 'Q', the number of queries. Each of the following Q lines contains one of the two types of operations: 
  • Id 0: where 'id' is the index of the stack (among the three) on which to operate. '0' implies popping the top element from the stack.
  • Id 1 ele: where 'id' is the index of the stack (among the three) and '1' implies pushing 'ele' on top of the stack.

Output Format:

For each query of type 0, output the element that was removed from the stack. If the stack is empty, output -1. Ensure each result is printed on a new line. 

Example:

Input:
2
5
0 1 5
1 0 7
0 0
0 1
2 1 3
3
0 2
1 2 8
0 2
Output:
-1
7
-1
8

Constraints:

  • 1 <= T <= 3
  • 0 <= Q, ele <= 100000
  • 0 <= id <= 2 (denoting one of the three stacks)

Note: If a pop operation is attempted on an empty stack, print -1.

Be the first one to answer
Add answer anonymously...
Cvent Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter