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 stackPOP- Pop and return the top value from stack
Arithmetic Operations:
ADD- Pop two values, push their sumSUB- Pop two values, push difference (second - first)MUL- Pop two values, push their product
Control Flow:
JMP address- Jump to instruction at given addressJEQ address- Jump if top two stack values are equalHALT- 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code