Evaluate Arithmetic Expressions and Decode Nested Run-Length Strings
Stacks & QueuesModel answerLast updated
Implement two production-ready string parsers: an arithmetic evaluator supporting basic operators and precedence, and a nested string expansion utility.
This task consists of two distinct string parsing subproblems commonly used to test custom parsing, state machine management, stack manipulation, and robust error handling.
Task 1: Arithmetic Expression Evaluator
Write a function that parses and evaluates arithmetic expression strings.
- Supported Operations: Addition (
+), Subtraction (-), Multiplication (*), Division (/), parenthesized subexpressions(), and unary negation (e.g.,-5,3*-(2+1)). - Division Behavior: Integer division truncating toward zero (e.g.,
-7 / 2 = -3). - Data Types & Overflow: Inputs are integers. All numbers and intermediate calculation values must fit within signed 64-bit integer limits ($-2^{63}$ to $2^{63} - 1$).
- Malformed Expressions & Errors: The parser must detect invalid tokens, division by zero, integer overflow/underflow, syntax errors (e.g.,
5 ++ 3,(), mismatched parentheses), and raise a specific exception. - File Processing: Provide a solution for reading an input stream or file with millions of lines, explaining memory limits and line-buffering trade-offs.
Task 2: Nested Run-Length Decoder
Write a function that decompresses encoded strings following the pattern k[sub_string], where sub_string inside the brackets is repeated exactly k times.
- Nesting: Brackets can be nested arbitrarily, such as
2[a3[bc]]$\rightarrow$abcbcbcabcbcbc. - Counts:
kis a non-negative integer and can have multiple digits (e.g.,10[a]). A multiplier of0yields an empty string. - Character Encoding: The implementation must correctly handle arbitrary characters (including multi-byte UTF-8 characters) inside or outside brackets.
- Validation: Detect syntax errors such as missing counts, unclosed brackets, dangling close brackets, or non-digit counts before a
[. - Complexity: Achieve $O(N)$ runtime relative to output length and discuss iterative stack versus recursive implementations.
Hints
Hint 1
Use an explicit state flag like `expect_operand` in the arithmetic evaluator to cleanly distinguish between binary subtraction and unary negation.
Hint 2
For integer division, standard Python `//` floors towards negative infinity. Adjust negative division results to truncate toward zero.
Hint 3
When decoding nested strings, maintain a stack of `(previous_string, repeat_count)` tuples whenever you encounter an opening bracket `[`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Arithmetic Expression Evaluator
Approach & Algorithm
To parse and evaluate arithmetic expressions in a single pass without building an explicit Abstract Syntax Tree (AST), we can use Dijkstra's Shunting-Yard algorithm modified to evaluate operators on the fly using two stacks:
vals: Holds intermediate scalar values (operands).ops: Holds pending operators and open parentheses.
State Tracking & Unary Operators
A common failure point in expression parsers is distinguishing binary subtraction (a - b) from unary negation (-a). We maintain a boolean flag expect_operand, initialized to True at the start of the expression or immediately after an open parenthesis ( or binary operator.
- If we encounter
-whenexpect_operandisTrue, it is a unary negation. We push a special high-precedence operator symbol'u'toops. - If we encounter
+whenexpect_operandisTrue, it is a unary plus (a no-op, which can be safely ignored). - If we see a digit when
expect_operandisFalse, or an operator whenexpect_operandisTrue(and it is not unary-or+), a syntax error is raised.
Operator Precedence
Precedence rules dictate evaluation order:
- High precedence: Unary
'u'(precedence level 3) - Medium precedence:
*,/(precedence level 2) - Low precedence:
+,-(precedence level 1)
When pushing a binary operator, we first pop and evaluate operators from ops with greater than or equal precedence. Left-associativity is naturally preserved by using the $\ge$ condition.
Python Implementation
import sys
INT_MIN = -(2**63)
INT_MAX = 2**63 - 1
PRECEDENCE = {'+': 1, '-': 1, '*': 2, '/': 2, 'u': 3}
class ExpressionError(Exception):
"""Custom exception raised for any invalid expression."""
pass
def _apply_op(ops: list, vals: list) -> None:
if not ops:
raise ExpressionError("Malformed expression: missing operator.")
op = ops.pop()
if op == 'u':
if not vals:
raise ExpressionError("Malformed expression: missing operand for unary minus.")
val = vals.pop()
res = -val
else:
if len(vals) < 2:
raise ExpressionError("Malformed expression: insufficient operands.")
b = vals.pop()
a = vals.pop()
if op == '+':
res = a + b
elif op == '-':
res = a - b
elif op == '*':
res = a * b
elif op == '/':
if b == 0:
raise ExpressionError("Division by zero encountered.")
# Truncate toward zero for signed integer division
res = int(a / b)
if not (INT_MIN <= res <= INT_MAX):
raise ExpressionError("64-bit integer overflow/underflow detected.")
vals.append(res)
def evaluate(expr: str) -> int:
vals = []
ops = []
expect_operand = True
i = 0
n = len(expr)
while i < n:
c = expr[i]
if c.isspace():
i += 1
continue
if '0' <= c <= '9':
if not expect_operand:
raise ExpressionError(f"Unexpected number at index {i}")
# Extract entire multi-digit number
start = i
while i < n and '0' <= expr[i] <= '9':
i += 1
num = int(expr[start:i])
if not (INT_MIN <= num <= INT_MAX):
raise ExpressionError(f"Number out of 64-bit range at index {start}")
vals.append(num)
expect_operand = False
continue # i was incremented in the inner loop
elif c == '(':
if not expect_operand:
raise ExpressionError(f"Unexpected '(' at index {i}")
ops.append('(')
expect_operand = True
elif c == ')':
if expect_operand:
raise ExpressionError(f"Unexpected ')' at index {i}")
while ops and ops[-1] != '(':
_apply_op(ops, vals)
if not ops:
raise ExpressionError(f"Unmatched closing parenthesis at index {i}")
ops.pop() # Remove '('
expect_operand = False
elif c in '+-*/':
if expect_operand:
if c == '-':
ops.append('u')
elif c == '+':
pass # Unary plus is a no-op
else:
raise ExpressionError(f"Unexpected binary operator '{c}' at index {i}")
else:
while ops and ops[-1] != '(' and PRECEDENCE.get(ops[-1], 0) >= PRECEDENCE[c]:
_apply_op(ops, vals)
ops.append(c)
expect_operand = True
else:
raise ExpressionError(f"Invalid character '{c}' at index {i}")
i += 1
if expect_operand:
raise ExpressionError("Unexpected end of expression.")
while ops:
if ops[-1] == '(':
raise ExpressionError("Unmatched opening parenthesis.")
_apply_op(ops, vals)
if len(vals) != 1:
raise ExpressionError("Invalid expression structure.")
return vals[0]
def evaluate_stream(file_object, output_stream=sys.stdout) -> None:
"""Processes large files line-by-line using streaming."""
for line_num, line in enumerate(file_object, 1):
clean_line = line.strip()
if not clean_line:
continue
try:
res = evaluate(clean_line)
output_stream.write(f"{res}\n")
except ExpressionError as err:
output_stream.write(f"Line {line_num} ERROR: {err}\n")
Complexity & Edge Cases
- Time Complexity: $O(L)$ per line, where $L$ is the length of the string. Each character and operator is pushed and popped at most once.
- Space Complexity: $O(D)$ where $D$ is the maximum nesting depth of parentheses and precedence levels. Intermediate stack operations continuously collapse expressions.
- Streaming Considerations: Iterating over a file line-by-line reads data lazily in memory buffers (typically 8KB chunks). Memory consumption remains bounded by the maximum single line length rather than total file size.
Part 2: Nested Run-Length Decoder
Approach
We maintain a stack containing tuples of (accumulated_string, repetition_count) corresponding to open nested scopes.
- Digits (
0-9): Build up the current multiplier numberk. - Opening Bracket
[: Push(current_string, k)onto the stack, then resetcurrent_string = ""andk = 0. - Closing Bracket
]: Pop(prev_string, count)from the stack. The updated string becomesprev_string + (current_string * count). - Regular Characters: Append directly to
current_string.
String Encoding Nuance
In Python, strings treat Unicode code points natively, making UTF-8 character extraction straightforward. In byte-oriented languages (like C++ or Go), iterating must be performed over UTF-8 standard multi-byte codepoints/runes rather than raw individual bytes.
def decode_string(s: str) -> str:
stack = []
current_str = []
current_num = 0
num_building = False
for i, char in enumerate(s):
if '0' <= char <= '9':
current_num = current_num * 10 + int(char)
num_building = True
elif char == '[':
if not num_building:
raise ValueError(f"Missing count before '[' at index {i}")
stack.append((''.join(current_str), current_num))
current_str = []
current_num = 0
num_building = False
elif char == ']':
if num_building:
raise ValueError(f"Dangling count without '[' at index {i}")
if not stack:
raise ValueError(f"Unmatched ']' at index {i}")
prev_str, count = stack.pop()
current_str = [prev_str + (''.join(current_str) * count)]
else:
if num_building:
raise ValueError(f"Number not followed by '[' at index {i}")
current_str.append(char)
if stack:
raise ValueError("Unmatched '[' remaining at end of string.")
if num_building:
raise ValueError("Trailing unattached repeat count at end of string.")
return ''.join(current_str)
Complexity Analysis
- Time Complexity: $O(N)$, where $N$ is the total expanded output length. Constructing each repeated block takes time proportional to the repeated output size.
- Space Complexity: $O(N + D)$, where $N$ is the size of the decoded result stored in output buffers and $D$ is the maximum bracket nesting depth.
- Iterative vs. Recursive:
- An iterative approach (used above) avoids call stack limits (e.g., Python's default stack limit of 1000 frames) and reduces function invocation overhead.
- A recursive approach relies on implicit function frames. While conceptually clean, deep nesting can lead to stack overflow exceptions on adversarial inputs.