Bytecode Compiler - Problem
Design and implement a bytecode compiler for a simple expression language that targets a stack-based virtual machine.
Your task: Given a mathematical expression as a string, compile it into a sequence of bytecode instructions that can be executed on a stack-based VM.
Supported Operations:
- Numbers: integers (e.g.,
42,-5) - Binary operators:
+,-,*,/ - Parentheses for grouping:
(,)
Bytecode Instructions:
PUSH n- Push number n onto stackADD- Pop two values, push their sumSUB- Pop two values, push (second - first)MUL- Pop two values, push their productDIV- Pop two values, push (second / first)
Example: Expression "3 + 4 * 2" should compile to ["PUSH 3", "PUSH 4", "PUSH 2", "MUL", "ADD"]
Note: Follow standard operator precedence (* and / before + and -) and left-to-right associativity.
Input & Output
Example 1 — Basic Expression with Precedence
$
Input:
expression = "3 + 4 * 2"
›
Output:
["PUSH 3", "PUSH 4", "PUSH 2", "MUL", "ADD"]
💡 Note:
Multiplication has higher precedence, so 4 * 2 is computed first: PUSH 4, PUSH 2, MUL (stack now has [3, 8]), then ADD gives 11
Example 2 — Parentheses Override Precedence
$
Input:
expression = "(3 + 4) * 2"
›
Output:
["PUSH 3", "PUSH 4", "ADD", "PUSH 2", "MUL"]
💡 Note:
Parentheses force addition first: PUSH 3, PUSH 4, ADD (stack: [7]), PUSH 2, MUL gives 14
Example 3 — Simple Addition
$
Input:
expression = "5 + 7"
›
Output:
["PUSH 5", "PUSH 7", "ADD"]
💡 Note:
Basic addition: push both operands, then ADD instruction pops them and pushes sum (12)
Constraints
- 1 ≤ expression.length ≤ 1000
- Expression contains only digits, operators (+, -, *, /), parentheses, and spaces
- All intermediate results fit in 32-bit signed integer
- No division by zero
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code