KatInterview

Parse and Evaluate Simple Arithmetic Tokens

StringsAuto-graded · 17 test cases
EasyAuto-gradedStringsstringstokenizingparsing

Last updated

Tests the ability to tokenize a raw arithmetic string into numbers and operators, then evaluate left-to-right respecting only + and - operations.

Parse and Evaluate Simple Arithmetic Tokens

You are given a string representing a simple arithmetic expression containing non-negative integers, and the operators + and -. Your task is to tokenize the string and evaluate it.

The expression is evaluated strictly left-to-right (no operator precedence — there is no * or /). Tokens are separated by zero or more spaces.

Write a function that takes such a string and returns the integer result of evaluating it.

Rules

  • The expression always starts with a non-negative integer.
  • Operators are always binary (no unary minus).
  • Numbers are non-negative integers (may be multi-digit).
  • There are no parentheses.
  • There may be multiple spaces (including none) between tokens.
  • Leading and trailing spaces are possible.
  • A string containing only a single number (no operators) is valid.

Constraints

  • 1 <= len(expression) <= 2000
  • All numbers in the expression are in the range [0, 10^9].
  • The expression always contains at least one number.
  • The expression is always valid (no malformed tokens, no division, no multiplication).
  • The result may be negative (e.g., "3 - 10").
  • The result fits in a standard Python int.

Examples

Example 1

Input: evaluate_expression('10 + 3 - 2')

Output: 11

Example 2

Input: evaluate_expression(' 42 ')

Output: 42

Example 3

Input: evaluate_expression('100 - 200 + 50')

Output: -50

Hints

Hint 1

Split the problem into two phases: first collect all tokens (numbers and operators) from the string, then walk through them to compute the result.

Hint 2

You can iterate character by character, accumulating digit characters into a current number buffer and emitting a token whenever you hit a non-digit (non-space) character or the end of the string.

Hint 3

Once you have a flat list of tokens, process them with a simple index walk: keep a running total and a pending operator (+/-), applying each operator as you encounter the next number.