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 stack
  • ADD - Pop two values, push their sum
  • SUB - Pop two values, push (second - first)
  • MUL - Pop two values, push their product
  • DIV - 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
INPUTMathematical Expression3 + 4 * 23+4*2Numbers and operatorswith precedence rulesALGORITHMShunting Yard Compiler1Tokenize expression2Use operator stack3Handle precedence (* before +)4Output postfix notationOp Stack: [+]Output: [3,4,2,*,+]RESULTStack VM Bytecode"PUSH 3""PUSH 4""PUSH 2""MUL""ADD"Stack execution:3, 4, 2 → 4*2=8 → 3+8=11Key Insight:The Shunting Yard algorithm uses operator precedence and a stack to convert infixexpressions directly to postfix bytecode, respecting mathematical order of operations.TutorialsPoint - Bytecode Compiler | Shunting Yard Algorithm
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
23.4K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen