Mini Spreadsheet: Cell Formulas and Cycle Detection
Data Structure DesignAuto-graded · 12 test casesLast updated
Tests dependency graph modeling, cycle detection on writes, and correct value propagation across a simple formula-based spreadsheet engine.
Mini Spreadsheet: Cell Formulas and Cycle Detection
You are building the core logic for a tiny spreadsheet engine. The engine processes a sequence of operations and must return one result per operation.
Cell Names
A cell name is one or more letters followed by one or more digits, for example A1, B12, or AA3. Cell names are case-insensitive; a1 and A1 refer to the same cell.
Cell Content
Content stored in a cell is one of two forms:
- A plain integer, such as
7or42. - A formula, which begins with
=and adds together one or more terms separated by+. Each term is either a plain integer or a cell reference, for example=A1+B2+5.
Operations
Each operation is a string, and its arguments are a list of strings:
| Operation | Arguments | Returns |
|---|---|---|
set_cell | [cell, content] | True if the write succeeded, False if it was rejected |
get_cell | [cell] | The integer value of the cell |
set_cell rules:
- If storing the new content would create a circular dependency (directly or through a chain of references), the write is rejected: return
Falseand leave the cell's previous content unchanged. - Otherwise, store the content and return
True.
get_cell rules:
- Return the computed integer value of the cell.
- A cell that has never been written evaluates to
0. - If the cell holds a plain integer, return that integer.
- If the cell holds a formula, evaluate it by summing each term, resolving any cell references recursively.
Circular Dependency Policy
A circular dependency occurs when following the chain of references from a cell eventually leads back to itself. Examples:
- Setting
A1 = =A1is a self-cycle. - Setting
A1 = =B1whileB1 = =A1would form a two-cell cycle.
When a write would create a cycle, reject it entirely. The sheet must remain exactly as it was before that write was attempted.
Propagation
Because values are computed at read time by recursively resolving references, any update to a cell is automatically reflected the next time any cell that (directly or indirectly) depends on it is read. No extra propagation step is required.
Constraints
1 ≤ len(operations) == len(arguments) ≤ 1000- Every operation string is either
"set_cell"or"get_cell". - Cell names match
[A-Za-z]+[0-9]+. - Formula terms are either valid cell names or integers matching
[+-]?\d+. - Plain integer content and integer terms in formulas fit in a 32-bit signed integer.
- At most 200 distinct cells are live at any one time.
- There are no operators other than
+in formulas.
Examples
Example 1
Input: spreadsheet_engine(['set_cell', 'set_cell', 'get_cell', 'set_cell', 'get_cell', 'get_cell'], [['A1', '7'], ['B1', '=A1+5'], ['B1'], ['A1', '10'], ['B1'], ['A1']])
Output: [True, True, 12, True, 15, 10]
Example 2
Input: spreadsheet_engine(['set_cell', 'set_cell', 'set_cell', 'set_cell', 'get_cell', 'get_cell'], [['A1', '=B1+1'], ['B1', '=A1'], ['B1', '=3'], ['A1', '=B1+1'], ['A1'], ['B1']])
Output: [True, False, True, True, 4, 3]
Hints
Hint 1
Think of the cells as nodes in a directed graph where an edge from X to Y means 'X's formula references Y'. Cycle detection is then reachability: before accepting a write, check whether the cell being written is already reachable from any cell it would reference.
Hint 2
You only need to store the raw content string for each cell. When get_cell is called, walk the formula recursively to compute the value on the fly — this keeps set_cell simple and avoids a separate cache invalidation step.
Hint 3
When a set_cell is rejected, the sheet must be completely unchanged. Since you run the cycle check before touching the contents dictionary, a rejection naturally requires no rollback.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core data model
The engine stores one thing per cell: its raw content string (either a plain integer like "7" or a formula like "=A1+B2+5"). Nothing else needs to be persisted. Values are computed fresh on every get_cell call by recursively resolving references, so there is no cache to invalidate when a cell changes.
Dependency graph and cycle detection
Think of the cells as nodes in a directed graph. A directed edge from cell X to cell Y means "X's formula mentions Y." The graph must remain acyclic at all times — that is the central invariant.
When set_cell(C, formula) is called, the new formula introduces edges from C to each cell it references. A cycle would exist if and only if C is already reachable from at least one of those referenced cells (following existing edges). So the check is: for each reference R in the new formula, do a DFS/BFS from R through the current graph and see whether you can reach C. If yes, reject the write.
Because the check runs before any state is changed, a rejection requires zero rollback — the contents dictionary is untouched.
get_cell evaluation
Walk the content string recursively. A plain integer returns immediately. A formula splits on +, then each term is either an integer literal (added directly) or a cell name (resolved recursively). An active set threads through the recursion as a defensive guard against any cycle that bypassed the write-time check; in a correct implementation it should never trigger.
Why this is correct
- The cycle check is complete: it visits every cell reachable from each new reference using the current graph state.
- The check is conservative: if C appears anywhere in the reachable set of any reference, the write is refused.
- Because writes either fully succeed or fully fail, the invariant "the graph is always a DAG" is preserved after every operation.
- Overwriting a cell with new content automatically drops its old references because only the latest content string is stored; the next cycle check or evaluation will use the new dependency set.
Complexity
Let N be the number of live cells and E be the total number of reference edges.
| Operation | Time | Space |
|---|---|---|
set_cell | O(N + E) — DFS from each new reference | O(N) for the DFS visited set |
get_cell | O(N + E) — recursive evaluation | O(N) for the call stack |
With at most 200 live cells the constants are small and both operations are fast in practice.
Reference solution
import re
from typing import List
_CELL_RE = re.compile(r"^[A-Za-z]+[0-9]+$")
def spreadsheet_engine(operations: List[str], arguments: List[List[str]]) -> List[object]:
# Maps uppercase cell name -> raw content string (int literal or formula).
contents = {}
results = []
def parse_refs(content: str) -> list:
"""Return the list of cell references that appear in content.
Raises ValueError if content is neither a valid integer nor a valid formula."""
if not content.startswith("="):
int(content) # validates that it is a plain integer
return []
refs = []
for term in content[1:].split("+"):
term = term.strip()
if _CELL_RE.fullmatch(term):
refs.append(term.upper())
elif not re.fullmatch(r"[+-]?\d+", term):
raise ValueError(f"Invalid formula term: {term!r}")
return refs
def can_reach(start: str, target: str) -> bool:
"""Return True if 'target' is reachable from 'start' by following references."""
stack = [start]
visited = set()
while stack:
current = stack.pop()
if current == target:
return True
if current in visited:
continue
visited.add(current)
if current in contents:
stack.extend(parse_refs(contents[current]))
return False
def evaluate(cell: str, active: set) -> int:
"""Recursively compute the integer value of a cell.
'active' tracks the cells currently on the call stack to catch
any cycle that somehow slipped through (defensive guard)."""
cell = cell.upper()
if cell in active:
raise ValueError(f"Circular reference detected at {cell}")
if cell not in contents:
return 0
content = contents[cell]
if not content.startswith("="):
return int(content)
active.add(cell)
total = 0
for term in content[1:].split("+"):
term = term.strip()
if _CELL_RE.fullmatch(term):
total += evaluate(term, active)
else:
total += int(term)
active.remove(cell)
return total
for operation, args in zip(operations, arguments):
if operation == "set_cell":
cell, content = args[0].upper(), args[1]
refs = parse_refs(content)
# Reject the write if storing this formula would create a cycle.
# We check BEFORE modifying contents so no rollback is needed.
if any(can_reach(ref, cell) for ref in refs):
results.append(False)
else:
contents[cell] = content
results.append(True)
elif operation == "get_cell":
results.append(evaluate(args[0], set()))
return results