KatInterview

Evaluate a Ternary-Chained Arithmetic Expression

Stacks & QueuesAuto-graded · 17 test cases
HardAuto-gradedStacks & Queuesstacksexpression evaluationparsing

Last updated

Tests expression evaluation using a monotonic/operator-precedence stack to correctly parse and compute a string containing +, -, *, /, parentheses, and nested ternary operators.

Evaluate a Ternary-Chained Arithmetic Expression

You are given a string expr representing an arithmetic expression that may also contain ternary conditionals. Your task is to evaluate it and return the integer result.

Expression grammar

The expression is built from the following rules (listed in order of increasing precedence):

  1. Ternary: condition ? true_branch : false_branch

    • The condition is any sub-expression. If it evaluates to a non-zero integer it is truthy; 0 is falsy.
    • Ternary associates right-to-left: a ? b : c ? d : e means a ? b : (c ? d : e).
  2. Addition / Subtraction: +, - (left-to-right, equal precedence)

  3. Multiplication / Integer Division: *, / (left-to-right, equal precedence, higher precedence than +/-)

    • Division is truncated toward zero (Python's int(a / b), not a // b).
  4. Unary minus: -expr (highest precedence among operators)

  5. Parentheses: (expr) override any precedence.

  6. Atoms: non-negative integer literals (no leading zeros except the literal 0 itself).

Parsing specifics

  • Tokens are: integer literals, (, ), +, - (binary or unary), *, /, ?, :.
  • Whitespace may appear anywhere between tokens and must be ignored.
  • Integer literals fit in a 32-bit signed integer before evaluation; intermediate and final results fit in a 64-bit signed integer.
  • Ternary branches: the : of a ternary is always the one matching the nearest unmatched ? (right-to-left association is naturally handled by the grammar).
  • Ternary has lower precedence than all arithmetic, so 1+2 ? 3*4 : 5-6 means (1+2) ? (3*4) : (5-6) → 12.

Your task

Implement evaluate_ternary_expr(expr: str) -> int that returns the integer value of the expression.

Constraints

  • 1 ≤ len(expr) ≤ 2000
  • The expression is always syntactically valid.
  • Integer literals are in the range [-2^31, 2^31 - 1] (after applying any unary minus).
  • Intermediate and final values fit in a 64-bit signed integer.
  • Ternary operators may be nested up to depth 50.
  • Parentheses may be nested up to depth 50.
  • Division by zero will not appear in any test case.
  • There is no exponentiation or modulo operator.

Examples

Example 1

Input: evaluate_ternary_expr('1 + 2 * 3')

Output: 7

Example 2

Input: evaluate_ternary_expr('1 ? 10 + 5 : 20 - 3')

Output: 15

Example 3

Input: evaluate_ternary_expr('0 ? 99 : 1 ? 42 : 7')

Output: 42

Hints

Hint 1

Tokenize first: walk the string once to emit a clean list of tokens (integers, operators, parens). Then write a recursive-descent parser with one function per precedence level — ternary at the bottom, then additive, then multiplicative, then unary, then primary (atoms and parenthesised groups). This completely avoids manual stack juggling for precedence.

Hint 2

Ternary right-associativity falls out naturally from recursive descent: after you parse the condition and consume '?', parse the true-branch by calling your ternary-level function recursively, then expect ':', then parse the false-branch the same way. Because the recursive call consumes the entire remaining ternary chain, right-association is free.

Hint 3

Integer division truncated toward zero is NOT the same as Python's '//' for negative operands (e.g. -7 / 2 should be -3, but -7 // 2 is -4). Use int(a / b) or the sign-aware formula: -((-a) // b) when signs differ.