Problem · Graph

Spreadsheet Formula Evaluator

Learn this problem
HardPika logoPikaFULLTIMEPHONE SCREEN

Problem 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 expression replaces 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 cell recursively evaluates the cell using the latest committed spreadsheet state.

Required behavior

  • A successful SET returns OK.
  • If a SET would introduce a direct or indirect circular reference, return ERROR and preserve the complete prior state.
  • A GET returns the decimal value of the cell, or ERROR if 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 SET can 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 A through Z and 26 rows 1 through 26.
  • 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.
drafts saved locally
public String[] solveSpreadsheetFormulaEvaluator(String input) {
    // write your code here
}
input"SET A1 10\nSET A1 20\nSET B1 = A1 + 10\nGET A1\nGET B1\nSET A1 = A1 + 10\nGET A1"
expected["OK", "OK", "OK", "20", "30", "ERROR", "20"]
checking account