Skip to the code
cf.
+50 XP

#630 Evaluate a Spreadsheet Formula

hard

A lightweight spreadsheet in the browser evaluates formulas like =A1*(B2+3)-4/2. Write evaluateFormula(formula, cells) that returns the formula's value.

  • The formula may start with =, which is ignored. Spaces can appear anywhere between tokens.
  • Tokens are whole numbers (digits only), cell names (capital letters followed by digits, like A1 or BC12), the operators + - * /, and parentheses.
  • A cell's value is cells[name]; a cell missing from cells counts as 0.
  • * and / bind tighter than + and -, operators of the same level go left to right, and - can also be a unary minus (as in -A1 or 2*-3). / divides and truncates toward zero.

Example 1

Input: formula = "=A1*(B2+3)-4/2", cells = {"A1":2,"B2":5}
Output: 14

2 * (5 + 3) - 2 is 14.

Example 2

Input: formula = "=-C3 + 7 / 2", cells = {"C3":4}
Output: -1

-4 + 3 (7 / 2 truncates to 3) is -1.

Constraints

  • 1 <= formula.length <= 10^4
  • The formula is valid and never divides by zero.
  • All values and intermediate results are whole numbers with absolute value below 2^31.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).