Problem · String

Spreadsheet Formula Dependencies

Learn this problem
HardAmazon Web Services logoAmazon Web ServicesNEW GRADONSITE INTERVIEW

Problem statement

Simulate a spreadsheet whose cells are labeled from A1 through Z26. Every cell is initially unset and evaluates to 0.

Process a finite sequence of commands:

  • SET cell value stores a signed integer and replaces any formula previously stored in that cell.
  • FORMULA cell term+term+... stores an addition formula and replaces any previous contents. Each term is either a nonnegative integer literal or a cell label. A cell label may appear more than once.
  • GET cell evaluates that cell using the spreadsheet's current contents.

Formula references remain live: changing a referenced cell changes every later GET whose dependency chain reaches it. Every represented formula assignment keeps the dependency graph acyclic.

Return one integer for every GET command, in command order.

Function

evaluateSpreadsheet(operations: String[]) → int[]

Examples

Example 1

operations = ["SET A1 5","SET B1 7","FORMULA C1 A1+B1","GET C1","SET A1 10","GET C1"]return = [12,17]

The first GET C1 evaluates 5 + 7 = 12. After A1 changes to 10, the stored formula remains live and evaluates to 10 + 7 = 17.

Example 2

operations = ["SET A1 3","FORMULA B1 A1+A1+2","GET B1","FORMULA C1 B1+A1","GET C1","SET A1 4","GET C1"]return = [8,11,14]

Repeated references count separately, so B1 = 3 + 3 + 2 = 8. Then C1 = 8 + 3 = 11. Updating A1 changes both levels, giving B1 = 10 and C1 = 14.

Example 3

operations = ["GET Z26","FORMULA A1 Z26+5","GET A1","SET Z26 2","GET A1","SET A1 -3","GET A1"]return = [0,5,7,-3]

An unset cell evaluates to 0. The formula in A1 observes the later update to Z26. The final SET replaces the formula in A1 with the literal -3.

Constraints

  • 1 ≤ operations.length ≤ 10000.
  • Every command uses a valid cell label from A1 through Z26.
  • Each formula contains at least one term and at most 676 terms.
  • The total number of formula terms across all commands is at most 200000.
  • Every formula assignment leaves the dependency graph acyclic.
  • Every stored integer and every evaluated result fits in a signed 32-bit integer.

More Amazon Web Services problems

drafts saved locally
public int[] evaluateSpreadsheet(String[] operations) {
    // Write your code here.
}
operations["SET A1 5","SET B1 7","FORMULA C1 A1+B1","GET C1","SET A1 10","GET C1"]
expected[12,17]
checking account