Problem Description
SnowCal is a simple programming language used to perform calculations. A SnowCal program keeps a single integer X in memory, initially set to zero, and repeatedly performs addition and multiplication operations on it.
Formally, the language has 5 operations:
- ADD Y → add Y to X
- MUL Y → multiply X by Y
- FUN F → begin the definition of a function with unique name F
- END → end of current function
- INV F → invoke function F
Write an interpreter that takes in the commands as an array of strings and returns the final value of X.
Problem Analysis
This question asks you to implement an interpreter for a simple language SnowCal. There is only one integer variable X (initially 0).
Key test points:
- Interpreter Design
- Function Definition & Scope Management
- Instruction Parsing
- State Management
This is a common System Design Coding question for mid-to-senior engineers.
Solution Implementation
class SnowCalInterpreter:
def __init__(self):
self.X = 0
self.functions = {} # Store function definitions
def interpret(self, commands):
i = 0
while i < len(commands):
cmd = commands[i]
if cmd == 'ADD':
value = int(commands[i + 1])
self.X += value
i += 2
elif cmd == 'MUL':
value = int(commands[i + 1])
self.X *= value
i += 2
elif cmd == 'FUN':
func_name = commands[i + 1]
i += 2
# Find function body (until END)
func_body = []
depth = 1 # Handle nested function definitions
while depth > 0:
if commands[i] == 'FUN':
depth += 1
elif commands[i] == 'END':
depth -= 1
if depth == 0:
break
func_body.append(commands[i])
i += 1
self.functions[func_name] = func_body
i += 1 # Skip END
elif cmd == 'INV':
func_name = commands[i + 1]
if func_name in self.functions:
# Recursively execute function body
self.interpret(self.functions[func_name])
i += 2
else:
i += 1
return self.X
def snowcal_interpreter(commands):
interpreter = SnowCalInterpreter()
return interpreter.interpret(commands)
Summary
SnowCal Interpreter question covers:
- Instruction Parsing: String processing and State Machine
- Function Management: Definition, Storage, Invocation
- Nesting Handling: Depth counting and Stack management
- State Maintenance: Variables and Call Stack
oavoservice specializes in interview coaching for Snowflake / Google / Amazon, offering OA support and real-time VO assistance. Contact us if you need help.
Need real interview questions? Contact WeChat Coding0201 immediately to get real questions.