Simple Virtual Machine - Problem

Build a stack-based virtual machine that executes bytecode instructions. Your VM should support the following operations:

Stack Operations:

  • PUSH value - Push a value onto the stack
  • POP - Pop and return the top value from stack

Arithmetic Operations:

  • ADD - Pop two values, push their sum
  • SUB - Pop two values, push difference (second - first)
  • MUL - Pop two values, push their product

Control Flow:

  • JMP address - Jump to instruction at given address
  • JEQ address - Jump if top two stack values are equal
  • HALT - Stop execution

Given an array of bytecode instructions, execute them and return the final stack state. Instructions are executed sequentially unless a jump occurs.

Input & Output

Example 1 — Basic Arithmetic
$ Input: instructions = ["PUSH 10", "PUSH 5", "ADD", "HALT"]
Output: [15]
💡 Note: Push 10 and 5 onto stack: [10, 5]. ADD pops both, pushes sum 15: [15]. HALT stops execution.
Example 2 — Multiple Operations
$ Input: instructions = ["PUSH 3", "PUSH 4", "MUL", "PUSH 2", "SUB"]
Output: [10]
💡 Note: Push 3, 4: [3, 4]. MUL gives [12]. Push 2: [12, 2]. SUB gives [10] (12-2=10).
Example 3 — Jump Operations
$ Input: instructions = ["PUSH 5", "PUSH 5", "JEQ 5", "PUSH 99", "HALT", "PUSH 100"]
Output: [100]
💡 Note: Push 5, 5: [5, 5]. JEQ compares top values (equal), jumps to instruction 5. Executes PUSH 100: [100].

Constraints

  • 1 ≤ instructions.length ≤ 1000
  • Each instruction is a valid bytecode operation
  • Jump addresses are within valid range [0, instructions.length)
  • Stack operations are performed only when sufficient elements exist

Visualization

Tap to expand
INPUT BYTECODEPUSH 10PUSH 5ADDHALTStack-based instructionsControl flow operationsArithmetic commandsVM EXECUTION1Parse instruction2Execute operation3Update stack/PC4Check for HALTStack State105Program Counter: 2FINAL RESULTStack: [15]Size: 1✓ Execution complete✓ HALT encountered✓ Stack contains resultKey Insight:A virtual machine is just a state machine - parse instructions into operations,maintain stack + program counter, and execute step by step with proper jump handling.TutorialsPoint - Simple Virtual Machine | Function Dispatch Table
Asked in
Google 35 Microsoft 28 Amazon 24 Meta 18
23.5K Views
Medium Frequency
~35 min Avg. Time
890 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