KatInterview

Validate-As-You-Go Calculator with Positive Integer Results

Trees & GraphsModel answer
MediumModel answerTrees & Graphsrecursionexpression-evaluationpost-order

Last updated

Evaluate a split-based arithmetic expression, returning false the moment any literal or intermediate value is non-positive or non-integer.

You are given a string containing an arithmetic expression. Its literals are integers written in decimal, and its binary operators are +, -, * and /. The expression may contain parentheses and spaces.

Compute the value of the expression under a strict rule: every literal, every operand and every intermediate result must be a strictly positive integer. If any part of the expression breaks this rule, the answer for the whole expression is Boolean false. A later operation can never "repair" an invalid part.

Provided helper

You may assume a function split(s) already exists. It breaks an expression at its outermost operation and returns one of:

  • a one-element tuple holding a literal, e.g. split("5") -> ("5",)
  • a three-element tuple (left, operator, right), e.g. split("(10 / 2) / 5") -> ("(10 / 2)", "/", "5")

The operand strings in the tuple may need further evaluation. You do not need to write a parser. Behaviour of split on malformed input is not defined, so you may assume inputs are well formed.

Rules

  • A literal is valid only if, after trimming whitespace and enclosing parentheses, it is a positive integer. Zero is invalid.
  • + and * use exact integer arithmetic.
  • a - b is invalid when the result is zero or negative.
  • a / b is invalid when b is zero or when a is not exactly divisible by b. Never round or truncate.
  • Return the final positive integer, or false if anything along the way is invalid.

Examples

"(3 + (3 * 5)) / 2"   ->  9
"((3 - 5) + 12) / 2"  ->  false   (3 - 5 is negative)
"8 / 12"              ->  false   (not an exact division)
"3 - 3"               ->  false   (zero is not positive)

What to deliver

Write evaluate(expression) using split. Explain your approach, justify its correctness, state its time and space complexity, and describe the edge cases you handle. Be ready to discuss what changes if nesting can be very deep.

Hints

Hint 1

Treat the output of `split` as a binary tree: a one-element tuple is a leaf and a three-element tuple is an internal node. What traversal order lets you compute a node only after its children?

Hint 2

Decide on an invariant for the return value: it is always either a strictly positive integer or `false`. Check for failure after each child returns, before doing any arithmetic.

Hint 3

Only subtraction and division can produce an invalid result from valid operands. Subtraction needs left > right; division needs a nonzero divisor and a zero remainder. In Python, remember `False == 0`, so test failure with `is False`.