Batch Spreadsheet Cell Evaluator with Cycle Rejection
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate setting and reading spreadsheet cells whose values are integers or sums of references, evaluating lazily and rejecting updates that would form cycles.
A spreadsheet holds named cells (uppercase letters followed by digits, e.g. A1, C12). Each cell is either empty or stores a definition: a literal integer, or a formula that adds together references to other cells and integer constants using + separators (for example "B1 + C1 + 5").
You are given a sequence of commands. Walk through them in order and produce one output per command.
Commands:
"setCell"with arguments[cell_name, value]. Thevalueis either anint(a literal) or astr(a formula). ReturnTrueif the assignment is accepted,Falseif it is rejected. An assignment is rejected exactly when it would make the cell reachable from itself: following the references of formulas (transitively) starting at any reference in the new formula leads back tocell_name. This includes a formula that references the cell itself. A rejected assignment must leave the entire sheet exactly as it was before the command — no partial changes."getCell"with arguments[cell_name]. Return the current integer value of that cell. A cell that was never assigned, or whose value ultimately depends on an unassigned cell, contributes0for that unassigned cell. If a formula references the same cell more than once, that cell's value is added once per occurrence.
Parsing details for formulas:
- The formula is split on
+. Each piece is trimmed of surrounding whitespace. - A trimmed piece matching
[A-Z]+[0-9]+entirely is a reference. - Otherwise the trimmed piece must be a valid optionally-signed integer, e.g.
"-3"or"12"; it contributes its integer value. - Constants may be negative or zero.
The output list contains, for each setCell, a True/False, and for each getCell, the evaluated integer.
Sample: ["setCell","setCell","setCell","getCell","setCell","getCell"] with [["B1",4],["C1",7],["A1","B1 + C1 + 5"],["A1"],["B1",10],["A1"]] yields [true,true,true,16,true,22].
Second sample: ["setCell","setCell","getCell","getCell","setCell","getCell"] with [["A1","B1 + C1"],["C1","A1"],["A1"],["C1"],["B1",3],["A1"]] yields [true,false,0,0,true,3] — the second assignment is rejected because it would form a cycle, so both A1 and C1 still evaluate to 0 until B1 is set.
Examples
Example 1
Input: run_spreadsheet_commands(['setCell', 'setCell', 'setCell', 'getCell', 'setCell', 'getCell'], [['B1', 4], ['C1', 7], ['A1', 'B1 + C1 + 5'], ['A1'], ['B1', 10], ['A1']])
Output: [True, True, True, 16, True, 22]
Example 2
Input: run_spreadsheet_commands(['setCell', 'setCell', 'getCell', 'getCell', 'setCell', 'getCell'], [['A1', 'B1 + C1'], ['C1', 'A1'], ['A1'], ['C1'], ['B1', 3], ['A1']])
Output: [True, False, 0, 0, True, 3]
Hints
Hint 1
Store each cell's definition as a list of terms (references or constants), then evaluate on demand with memoization per read.
Hint 2
An assignment forms a cycle exactly when the target cell is reachable from one of its new references by following forward formula edges. Check this before mutating anything so a rejection is atomic.
Hint 3
Duplicate references must count each occurrence; treat a literal integer as a formula with no references so you have only one storage shape.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep definitions, mapping each assigned cell to a normalized form: either a plain int, or a list of terms where a term is ("ref", name) or ("const", value). Unassigned cells are simply absent and evaluate to 0. This normalized shape removes the special case between literals and formulas.
Walk the commands in order:
setCell: if the value is anint, store it directly and returnTrue. Otherwise parse the formula into terms, gather its references, and check whether any reference can reach the target cell by following forward formula edges. That reachability test is an iterative DFS. If the target is reachable, returnFalseand leavedefinitionsuntouched, so the rejection is atomic. If not, store the parsed terms and returnTrue.getCell: evaluate with a fresh memo dictionary. A cell that is not a list is a literal or missing (0). A list sums each term, recursing into references and adding constants directly.
Why it is correct
A cycle exists in the dependency graph exactly when a set of forward edges forms a loop. A new formula for cell creates a loop only when some new reference has a forward path back to cell; checking reachability from each new reference to cell therefore catches exactly the bad updates, including self-references. Because we never mutate the dictionary before the check passes, all rejected commands leave the sheet in its prior state, which matches the required behavior for the second sample.
Evaluation sums terms literally over the current definitions, so duplicate references contribute their value once per appearance. Unassigned cells resolve to 0.
Complexity
Let V be assigned cells and E distinct reference edges. A setCell costs O(L + V + E) in the worst case, where L is the formula length for parsing and DFS/invalidation touch only the reachable subgraph, usually far smaller than the whole sheet. A getCell costs O(V + E) per read (O(1) for literals or unassigned cells) but each read is self-contained. Space is O(V + E).
import re
from typing import List
def run_spreadsheet_commands(operations: List[str], arguments: List[List[object]]) -> List[object]:
# Each assigned cell stores either a literal integer or a list of terms:
# ("ref", cell_name) or ("const", integer). Unassigned cells evaluate to zero.
definitions = {}
cell_pattern = re.compile(r"[A-Z]+[0-9]+\Z")
def parse_formula(formula):
terms = []
for raw_term in formula.split("+"):
token = raw_term.strip()
if cell_pattern.fullmatch(token):
terms.append(("ref", token))
else:
terms.append(("const", int(token)))
return terms
def reaches_target(start, target):
stack = [start]
visited = set()
while stack:
cell = stack.pop()
if cell == target:
return True
if cell in visited:
continue
visited.add(cell)
definition = definitions.get(cell)
if isinstance(definition, list):
stack.extend(name for kind, name in definition if kind == "ref")
return False
def evaluate(target):
memo = {}
def visit(cell):
if cell in memo:
return memo[cell]
definition = definitions.get(cell)
if definition is None:
return 0
if isinstance(definition, int):
memo[cell] = definition
return definition
value = 0
for kind, term in definition:
value += visit(term) if kind == "ref" else term
memo[cell] = value
return value
return visit(target)
results = []
for operation, args in zip(operations, arguments):
if operation == "setCell":
cell, value_or_formula = args
if type(value_or_formula) is int:
definitions[cell] = value_or_formula
results.append(True)
else:
terms = parse_formula(value_or_formula)
dependencies = [term for kind, term in terms if kind == "ref"]
# Reject atomically: leave any previous definition unchanged.
if any(reaches_target(dependency, cell) for dependency in dependencies):
results.append(False)
else:
definitions[cell] = terms
results.append(True)
elif operation == "getCell":
results.append(evaluate(args[0]))
else:
raise ValueError("Unknown operation")
return results