Problem · Array
Generic Stack Operation Sequence
Learn this problemProblem statement
Implement a stack over string values and execute each command in operations in order. The stack starts empty.
PUSH:value: pushvalueand outputOK.TOP: output the current top value, orEMPTYwhen the stack is empty.POP: remove and output the current top value, or outputEMPTYwhen the stack is empty.SIZE: output the current size as a decimal string.EMPTY: outputtruewhen the stack is empty andfalseotherwise.
Return one output for every input command. A popped element is destroyed from the logical stack immediately: later commands must not read it through retained internal storage or a stale reference. Your stack should support amortized constant-time PUSH and constant-time remaining operations.
Function
simulateGenericStack(operations: String[]) → String[]Examples
Example 1
operations = ["PUSH:alpha","PUSH:beta","TOP","SIZE","POP","TOP","EMPTY"]return = ["OK","OK","beta","2","beta","alpha","false"]The two pushes leave beta on top. Popping it destroys that stack element, so the next top is alpha.
Example 2
operations = ["TOP","POP","EMPTY","PUSH:x","POP","EMPTY"]return = ["EMPTY","EMPTY","true","OK","x","true"]Reading or popping an empty stack returns EMPTY. After pushing and popping x, the stack is empty again.
Example 3
operations = ["PUSH:a","PUSH:b","PUSH:c","POP","PUSH:d","TOP"]return = ["OK","OK","OK","c","OK","d"]After c is removed, pushing d makes d the new top.
Constraints
1 <= operations.length <= 100000- Each command is exactly
TOP,POP,SIZE,EMPTY, orPUSH:value. - Each pushed value contains 1 to 32 ASCII letters, digits, underscores, or hyphens.
- Pushed values are not equal to the reserved outputs
OK,EMPTY,true, orfalse.