Problem · Array

Generic Stack Operation Sequence

Learn this problem
MediumArista Networks logoArista NetworksFULLTIMEPHONE SCREEN

Problem statement

Implement a stack over string values and execute each command in operations in order. The stack starts empty.

  • PUSH:value: push value and output OK.
  • TOP: output the current top value, or EMPTY when the stack is empty.
  • POP: remove and output the current top value, or output EMPTY when the stack is empty.
  • SIZE: output the current size as a decimal string.
  • EMPTY: output true when the stack is empty and false otherwise.

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, or PUSH: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, or false.

More Arista Networks problems

drafts saved locally
public String[] simulateGenericStack(String[] operations) {
  // write your code here
}
operations["PUSH:alpha","PUSH:beta","TOP","SIZE","POP","TOP","EMPTY"]
expected["OK", "OK", "beta", "2", "beta", "alpha", "false"]
checking account