KatInterview

Evaluate Prize-Pool Formulas with Strictly Positive Whole Steps

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesparsingrecursive-descentexpression-evaluation

Last updated

Parse and evaluate an infix arithmetic string, rejecting it with False if any intermediate result is zero, negative, or a non-integer quotient.

A prize-pool calculator accepts formulas written as plain arithmetic text. A formula contains positive integer literals, the operators +, -, *, /, and parentheses. Precedence is the usual one: * and / bind tighter than + and -, and operators of equal precedence group left to right.

The formula describes splitting a pool into whole shares, so every value produced during evaluation must be a strictly positive integer. That covers each literal and each intermediate result, not just the final answer. If any step yields zero, a negative number, or a fraction, the whole formula is rejected, even if later steps would have "repaired" the value.

Implement:

def evaluate_share_formula(expression: str) -> int | bool:
    ...

Return the integer result if all steps are valid, otherwise return False.

Rules

  • A literal is a run of digits. The literal 0 is invalid.
  • Subtraction is invalid when the result would be zero or negative.
  • Division is invalid if the divisor is zero or if the division is not exact. No rounding or truncation is allowed.
  • Addition and multiplication of positive integers are always valid.
  • Whitespace between tokens is ignored.

Examples

evaluate_share_formula("((9 * 4) / 6) + 10")  # 36 -> 6 -> 16, returns 16
evaluate_share_formula("(20 - 6) / 2")        # 14 -> 7, returns 7
evaluate_share_formula("(5 - 9) + 100")       # 5-9 = -4 is invalid, returns False
evaluate_share_formula("15 / 4")              # not exact, returns False

In the third example -4 + 100 would be 96, but the negative intermediate already invalidates the formula.

Constraints

  • Input is always well-formed: digits, + - * /, balanced parentheses, optional spaces. There is no unary minus and no leading zeros.
  • Length is at most 500 characters and nesting depth at most 50.
  • Write your own parser. Do not use eval or a parsing library.

Explain your approach, state its complexity, and provide code.

Hints

Hint 1

Write the grammar down first: an expression is terms joined by + or -, a term is factors joined by * or /, and a factor is a number or a parenthesized expression. Each level maps to one function.

Hint 2

Evaluate while parsing instead of building a tree. Validate each value the moment it is created: after reading a literal and after every binary operation.

Hint 3

Use an exception to abort on the first invalid step so it unwinds through nested parentheses automatically, and catch it once at the top level to return False. Check division with the integer remainder, not floats.