Problem · Graph
Spreadsheet Formula Evaluator
Learn this problemProblem statement
Implement a small stateful spreadsheet whose cells are labeled A1 through Z26. Process a newline-delimited sequence of commands and return one result for every command, in order.
Command language
SET cell expressionreplaces the cell's current contents. An expression may begin with an optional=and then contains one or more nonnegative integer literals or cell labels joined by+. Whitespace around the equals sign and terms is optional.GET cellrecursively evaluates the cell using the latest committed spreadsheet state.
Required behavior
- A successful
SETreturnsOK. - If a
SETwould introduce a direct or indirect circular reference, returnERRORand preserve the complete prior state. - A
GETreturns the decimal value of the cell, orERRORif the cell is unset or evaluation reaches an unset reference. - A formula may be committed before all of its referenced cells are set. A later
SETcan make that formula evaluable.
Implement solveSpreadsheetFormulaEvaluator, which returns the command results as a string array.
Function
solveSpreadsheetFormulaEvaluator(input: String) → String[]Examples
Example 1
input = "SET A1 10\nSET A1 20\nSET B1 = A1 + 10\nGET A1\nGET B1\nSET A1 = A1 + 10\nGET A1"return = ["OK","OK","OK","20","30","ERROR","20"]The second command overwrites A1 with 20, so B1 evaluates to 30. The attempted self-reference is rejected, and the final read proves that A1 still contains 20.
Example 2
input = "SET A1 2\nSET B1 = A1 + A1 + 1\nSET C1 = B1 + A1\nGET C1\nSET A1 5\nGET C1"return = ["OK","OK","OK","7","OK","16"]Initially B1 = 5 and C1 = 7. After A1 becomes 5, recursive evaluation uses the new value, making B1 = 11 and C1 = 16.
Example 3
input = "SET A1 1\nSET B1 = A1 + 2\nSET C1 = B1 + 3\nSET A1 = C1 + 4\nGET A1\nGET C1"return = ["OK","OK","OK","ERROR","1","6"]Changing A1 to reference C1 would create the cycle A1 -> C1 -> B1 -> A1. The update is rejected, so the earlier values remain available.
Constraints
- The spreadsheet has exactly 26 columns
AthroughZand 26 rows1through26. 1 <= number of commands <= 10000.- The total number of expression terms is at most
200000. - Every command is syntactically valid, every cell label is in range, and every successful evaluation fits a signed 32-bit integer.
- Expressions contain only nonnegative integer literals, cell labels, optional whitespace, and the
+operator.