Problem · Stack

Stack Batch Removal

Learn this problem
MediumIMIMCNEW GRADOA

Problem statement

Implement a stack that accepts the following commands and performs the operations described:

  • push value: Push integer value onto the top of the stack.
  • pop: Pop the top element from the stack.
  • remove_lower value: Remove all current elements in the stack less than value.
  • remove_upper value: Remove all current elements in the stack more than value.

After each operation, output the current top element of the stack. If no such element exists, output "EMPTY".

The input array operations contains the command lines in order. Return one output string for each operation, in the same order as the lines the original program prints.

Function

stackBatchRemoval(operations: String[]) → String[]

Examples

Example 1

operations = ["push 3", "push 2", "push 4", "remove_lower 3", "remove_upper 3", "push 2", "pop", "pop"]return = ["3", "2", "4", "4", "3", "2", "3", "EMPTY"]
  1. Initially, the stack is empty.
  2. After push 3, the stack contains [3].
  3. After push 2, the stack contains [3, 2].
  4. After push 4, the stack contains [3, 2, 4].
  5. After remove_lower 3, the stack contains [3, 4].
  6. After remove_upper 3, the stack contains [3].
  7. After push 2, the stack contains [3, 2].
  8. After pop, the stack contains [3].
  9. After pop, the stack is empty.

Constraints

  • 1 <= n <= 2 * 10^5, the total number of lines or operations.
  • -10^9 <= value <= 10^9
  • It is guaranteed that pop will not be called on an empty stack.

More IMC problems

drafts saved locally
public String[] stackBatchRemoval(String[] operations) {
    // write your code here
}
operations["push 3", "push 2", "push 4", "remove_lower 3", "remove_upper 3", "push 2", "pop", "pop"]
expected["3", "2", "4", "4", "3", "2", "3", "EMPTY"]
checking account