1674. Tiny Stack Machine

Easy1.5 points estimatedStackSimulationString

A tiny calculator keeps numbers on a stack that starts empty. Each entry of program is one instruction: "PUSH v" puts the integer v on the stack, "POP" discards the top value, "DUP" pushes a copy of the top value, "SWAP" exchanges the top two values, and "ADD", "SUB" and "MUL" remove the top two values and push their sum, difference or product. For SUB the result is the second-from-top value minus the top value.

An instruction that does not have enough values on the stack is an error and stops the run. Return the value on top of the stack after the last instruction, or null if an error occurred or the stack ends up empty. Here 1 <= program.length <= 1000, -10^4 <= v <= 10^4, and every intermediate value is guaranteed to stay within [-10^15, 10^15], so 64-bit integers suffice. A single pass uses O(n) time and O(n) space.

Example 1

Input:
program = ["PUSH 3","PUSH 4","ADD"]
Output:
7
Explanation:

3 and 4 are added, leaving 7 on top.

Example 2

Input:
program = ["PUSH 10","PUSH 3","SUB"]
Output:
7
Explanation:

SUB computes the second-from-top value 10 minus the top value 3, giving 7.

Example 3

Input:
program = ["PUSH 5","POP","POP"]
Output:
null
Explanation:

The second POP finds an empty stack, so the answer is null.

Constraints

1 ≤ program.length ≤ 1000; -104 ≤ v ≤ 104; every intermediate value is guaranteed to lie in [-1015, 1015]

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…