KatInterview

Evaluate Arithmetic Expressions and Decode Nested Run-Length Strings

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesstackparsingstrings

Last 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: k is a non-negative integer and can have multiple digits (e.g., 10[a]). A multiplier of 0 yields 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 `[`.