Eager Formula Sheet with Cycle-Safe Updates
Trees & GraphsAuto-graded · 16 test casesLast updated
Simulate a mini spreadsheet where formulas are evaluated at write time, dependents update eagerly, and any write that would create a dependency cycle is rejected without changing state.
Eager Formula Sheet with Cycle-Safe Updates
You are given a sequence of spreadsheet operations and must simulate them on an in-memory sheet. The sheet supports two kinds of operations:
set_cell(label, value)writes a value into a cell. The value is either an integer or a formula string.get_cell(label)reads a cell's current value.
Operations are given as two parallel lists: operations[i] is the operation name and arguments[i] is its argument list. Return one result per operation in a list, in order. Only set_cell and get_cell produce results: get_cell contributes its value, and set_cell contributes True if the write was accepted or False if it was rejected. Each operation's result is appended in order.
Labels
A label is one or more ASCII letters followed by one or more digits, such as "A1", "b12", or "XY3". Labels are case-insensitive, so "a1" and "A1" refer to the same cell. Anything that does not match this shape is invalid and must raise ValueError.
Values and formulas
- An integer value (not a boolean) stores that constant in the cell.
- A string beginning with
=is a formula. Ignore all spaces in the formula. The remainder is split on+into terms. Each term is either a label (a reference to another cell) or an integer constant, which may have an optional leading-sign. Any other shape is invalid and must raiseValueError. - Any other value type (including booleans and non-
=strings) must raiseValueError.
Semantics
- A reference to a cell that has never been set contributes
0. A cell that has never been set reads as0throughget_cell. - A formula's value is the sum of its terms, using the current values of the referenced cells.
- Values are computed eagerly, at the moment of
set_cell.get_cellnever recomputes anything; it only reads stored values. - When a cell changes, every cell whose value depends on it, directly or transitively, must be brought up to date before
set_cellreturns. After every accepted write, every stored value must equal what a fresh evaluation of the sheet would produce. - If a write would create a dependency cycle, including a cell that references itself,
set_cellreturnsFalse. In that case the sheet is left exactly as it was before the call, and no cell changes. - Unknown operation names must raise
ValueError.
Constraints
1 <= len(operations) == len(arguments) <= 2000- Each
set_cellcall has exactly two arguments: a label and a value. Eachget_cellcall has exactly one argument: a label. - Every formula has at most 50 terms.
- Constants and stored integers fit in a 64-bit signed range, so Python's arbitrary-precision integers are sufficient.
- Results are returned as a list containing booleans for
set_celland integers forget_cell.
Your function must return the list of results described above.
Examples
Example 1
Input: run_sheet_ops(['set_cell', 'set_cell', 'get_cell', 'set_cell', 'get_cell', 'set_cell', 'get_cell'], [['A1', 10], ['A2', '=A1+20'], ['A2'], ['A1', 1], ['A2'], ['A1', '=A2+1'], ['A1']])
Output: [True, True, 30, True, 21, False, 1]
Example 2
Input: run_sheet_ops(['set_cell', 'set_cell', 'get_cell', 'set_cell', 'get_cell'], [['A1', '=B1+1'], ['B1', '=A1+1'], ['A1'], ['B1', 7], ['A1']])
Output: [True, False, 1, True, 8]
Example 3
Input: run_sheet_ops(['set_cell', 'set_cell', 'set_cell', 'get_cell'], [['A1', '=B1+C1'], ['B1', 4], ['C1', 6], ['A1']])
Output: [True, True, True, 10]
Hints
Hint 1
Model the sheet as a directed graph where each formula cell points to the cells it references. A write is rejected exactly when the new formula can reach the target cell by following existing references.
Hint 2
Before committing a new formula, do a search from its referenced cells through the current formulas. If the search reaches the target cell, including a direct self-reference, reject the write without modifying anything.
Hint 3
After an accepted write, recompute values in dependency order. A topological ordering over the formula cells, such as Kahn's algorithm, guarantees each cell's references are already updated when it is evaluated.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two maps: formulas stores each set cell's parsed terms (a plain integer is stored as a single constant term), and values stores each cell's current computed value.
For set_cell:
- Normalize the label to upper case and validate it.
- Parse the value. An integer becomes one constant term. A string starting with
=has spaces removed, is split on+, and each piece is validated as either a label or an integer. Anything else raisesValueError. - Cycle check: starting from the new formula's referenced cells, follow existing reference edges with an explicit stack. If the target cell is reached, the write would close a cycle, so return
Falseand leave all state untouched. This also covers self-references, since a self-reference makes the target itself appear among the starting references. - If there is no cycle, store the new terms and recompute.
For recomputation, build the dependency graph among set cells (edges from each referenced set cell to its dependents), compute in-degrees, and process cells with Kahn's algorithm. When a cell is dequeued, all of its referenced cells are already final, so its value is the sum of its constants and current referenced values (unset references count as 0).
get_cell only looks up the stored value, defaulting to 0 for unset cells.
Why it is correct
- Any accepted write produces a graph with no cycles, so Kahn's algorithm processes every formula cell exactly once, and each cell is evaluated only after all of its references are final. Every stored value therefore matches a fresh evaluation of the sheet.
- A cycle exists after the write exactly when the new formula can reach its own target through existing references. The search explores every reachable cell, so it detects cycles of any length. Rejected writes never modify
formulasorvalues, so the sheet is unchanged.
Complexity
Let n be the number of set cells and m the total number of formula terms.
- Cycle check: O(n + m) per
set_cell, because it may visit every stored formula once. - Recomputation: O(n + m) per accepted
set_cell, since the whole graph is rebuilt and processed. get_cell: O(1) average.- Space: O(n + m).
Reference solution
import re
from collections import deque
from typing import List
def run_sheet_ops(operations: List[str], arguments: List[List]) -> List:
formulas = {} # cell -> list of (kind, term); kind is "const" or "ref"
values = {} # cell -> current computed integer value
results = []
label_re = re.compile(r"^[A-Za-z]+[0-9]+$")
term_re = re.compile(r"^(?:[A-Za-z]+[0-9]+|[+-]?[0-9]+)$")
def normalize(label):
if not isinstance(label, str) or not label_re.fullmatch(label):
raise ValueError("invalid cell label")
return label.upper()
def would_cycle(target, terms):
# Walk the reference graph from the new formula's references.
stack = [term for kind, term in terms if kind == "ref"]
seen = set()
while stack:
cell = stack.pop()
if cell == target:
return True
if cell in seen:
continue
seen.add(cell)
for kind, term in formulas.get(cell, []):
if kind == "ref":
stack.append(term)
return False
def recompute_all():
defined = set(formulas)
indegree = {cell: 0 for cell in defined}
dependents = {cell: [] for cell in defined}
for cell, terms in formulas.items():
for kind, term in terms:
if kind == "ref" and term in defined:
indegree[cell] += 1
dependents[term].append(cell)
queue = deque(cell for cell in defined if indegree[cell] == 0)
while queue:
cell = queue.popleft()
total = 0
for kind, term in formulas[cell]:
total += term if kind == "const" else values.get(term, 0)
values[cell] = total
for dependent in dependents[cell]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
queue.append(dependent)
for operation, args in zip(operations, arguments):
if operation == "get_cell":
results.append(values.get(normalize(args[0]), 0))
elif operation == "set_cell":
cell = normalize(args[0])
value = args[1]
if isinstance(value, int) and not isinstance(value, bool):
terms = [("const", value)]
elif isinstance(value, str) and value.startswith("="):
expression = value[1:].replace(" ", "")
terms = []
for piece in expression.split("+"):
if not term_re.fullmatch(piece):
raise ValueError("invalid formula")
if piece[0].isalpha():
terms.append(("ref", normalize(piece)))
else:
terms.append(("const", int(piece)))
else:
raise ValueError("cell value must be an integer or formula")
if would_cycle(cell, terms):
results.append(False)
continue
formulas[cell] = terms
recompute_all()
results.append(True)
else:
raise ValueError("unknown operation")
return results