Problem · Graph

Spreadsheet Formula Evaluator

HardHarveyFULLTIMEPHONE SCREEN

Complete the function below. The function receives the full standard input as a single string and returns the exact standard output lines for a small spreadsheet engine.

Problem

Implement a spreadsheet with cell labels such as A1 and B10. The spreadsheet supports setting cells to integers or formulas, retrieving evaluated values, and detecting cycles.

A formula is a +-separated expression containing non-negative integer literals and/or cell labels. Operators other than + are not required.

Supported commands:

  • SET label value: set label to an integer or formula. Return OK if the assignment does not create a dependency cycle; otherwise leave the spreadsheet unchanged and return ERROR.
  • GET label: return the evaluated integer value of label. Return ERROR if the cell is unset or cannot be evaluated.

Cell dependencies are evaluated lazily or eagerly as you choose, but GET must always reflect the latest committed cell values.

Function Description

Complete solveSpreadsheetFormulaEvaluator. It has one parameter, String input, containing newline-separated commands. Return the stdout payload as an array of lines, without trailing newline characters.

Examples
01 · Example 1
input = "SET A1 10\nGET A1\nSET A2 A1+20\nGET A2\nSET A3 A1+A2+5\nGET A3"
return = ["OK","10","OK","30","OK","45"]

A2 references A1, and A3 references both A1 and A2.

02 · Example 2
input = "SET A1 10\nSET B1 A1+1\nSET A1 B1+1\nGET A1\nGET B1"
return = ["OK","OK","ERROR","10","11"]

The third command would create A1 -> B1 -> A1, so it is rejected and the previous values remain active.

Constraints

Cell labels consist of uppercase letters followed by digits, such as A1 or B10.

Formula expressions only need to support addition with +.

Assignments that introduce a cycle must be rejected.

More Harvey problems
drafts saved locally
public String[] solveSpreadsheetFormulaEvaluator(String input) {
    // write your code here
}
input"SET A1 10\nGET A1\nSET A2 A1+20\nGET A2\nSET A3 A1+A2+5\nGET A3"
expected["OK", "10", "OK", "30", "OK", "45"]
sign in to submit