KatInterview

Evaluate Simple Arithmetic String Expressions

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

Last updated

Tests ability to evaluate a string expression containing non-negative integers, +, -, *, / operators, and parentheses using a stack-based approach.

Evaluate Simple Arithmetic String Expressions

You are given a string expr representing a valid arithmetic expression. The expression may contain:

  • Non-negative integer literals (one or more digits)
  • The four binary operators: +, -, *, /
  • Parentheses ( and ) for grouping
  • Single space characters anywhere between tokens

Your task is to evaluate the expression and return the integer result.

Division is integer division that truncates toward zero (same behaviour as Python's int(a / b) — not floor division). For example, 7 / 2 = 3 and -7 / 2 = -3.

Operator precedence follows standard rules: * and / bind more tightly than + and -. Parentheses override precedence in the usual way.

You may not use Python's eval or compile built-ins.

Constraints

  • 1 ≤ len(expr) ≤ 2 000
  • The expression is always syntactically valid.
  • All integer literals in the expression are in the range [0, 10 000].
  • The final result and all intermediate results fit in a 32-bit signed integer ([-2 147 483 648, 2 147 483 647]).
  • The expression contains only the characters 0-9, +, -, *, /, (, ), and space.
  • There are no unary minus signs; every - is a binary operator between two values.

Examples

Example 1

Input: evaluate_expression('3 + 5')

Output: 8

Example 2

Input: evaluate_expression('10 + 2 * 6')

Output: 22

Example 3

Input: evaluate_expression('( 2 + 3 ) * ( 8 - 3 )')

Output: 25

Hints

Hint 1

Tokenize the string first into numbers and operator/bracket tokens, then process them; this separates concerns cleanly.

Hint 2

A classic two-stack approach works well: one stack for numbers (operands) and one stack for operators. When you see a ')', pop and apply operators until you reach the matching '('.

Hint 3

To respect precedence without recursion, apply a pending higher-precedence operator (* or /) immediately when you push a lower-precedence operator (+ or -) onto the operator stack.