1. It is guaranteed that there is at least one query of type βPOPβ.
Let there be the following 10 queries and βLIMITβ be 3.
[PUSH 3, PUSH 2, PUSH 1, INC 2 1, PUSH 1, POP, INC 3 3, POP, POP, POP].
Stack after 0th query, i.e PUSH 3, be [3]
Stack after 1st query, i.e PUSH 2, be [3, 2] (top to bottom of the stack is represented by right to the left of list)
Stack after 2nd query, i.e PUSH 1, be [3, 2, 1].
Stack after 3rd query, i.e INC 2 1, be [4, 3, 1]. We increment the bottom 2 elements by 1.
Stack after 4th query, i.e PUSH 1, be [4, 3, 1] as the size of the stack cannot exceed 3.
Stack after 5th query, i.e POP, be [4, 3] and we should return 1 for this query.
Stack after 6th query, i.e INC 3 3, be [7, 6] as stack size is less than 3, so we every element.
Stack after the 7th query, i.e POP, be [7] and we should return 6 for this query.
Stack after 8th query, i.e POP, be [] and we should return 7 for this query.
Stack after the 9th query, i.e POP, be [] and we should return -1 for this query.
Thus we should return an array/list [1, 6, 7, -1].
The first line contains a single integer βTβ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case will contain two space-separated integers βQβ and βLIMITβ, representing the number of queries, and maximum size of stack respectively.
The next βQβ lines of each test case consist of a string that represents the type of query and then 0 to 2 space-separated integers according to types of query.
For each test case, print space-separated integers returned by a query of type βPOPβ in the same order in which these queries are executed.
Output for every test case will be printed in a separate line.
You donβt need to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= Q <= 10000
1 <= LIMIT <= 10000
1 <= X <= 10000
1 <= K <= 10000
1 <= Y <= 10000
Where βTβ is the number of test cases, βQβ, βLIMITβ, representing the number of queries, and maximum size of stack respectively, and βXβ, βKβ, βYβ are integers described in problem statements.
Time limit: 1 sec
The basic idea is to simulate stack using vector/listβ. The PUSH and POP query can be performed in O(1) times, and for the query of type INC βKβ βYβ, we iterate over the first βKβ elements (If exist) and increment them by Y, it can take O(K) times.
The steps are as follows:
We can optimize the previous approach by keeping a vector/list ADD to track the increments operation, we only increment the value of the element at a time when it βPOPβ. This idea can be implemented as follow -:
Postorder Traversal
Postorder Traversal
Min Stack
Min Stack
Min Stack
Min Stack
Stock Span
Hills and Soldier
Hills and Soldier
Hills and Soldier
Next Greater Element II