Build a Dependency-Aware Cell Calculator with Cycle Checks
Data Structure DesignModel answerLast updated
Design an in-memory grid of numeric and formula cells in Python, reject circular dependencies, allow shared references, and compare lazy evaluation against eager recomputation with caching.
Build a small in-memory grid, similar to a spreadsheet, as a Python class. It exposes three operations:
set_cell(cell, value): store a plain number in the named cell.set_formula(cell, formula): store a formula string in the named cell. Formulas use cell names, numeric literals and the operators+,-,*,/.get_cell(cell): return the current numeric value of the cell.
set_cell("A1", 5)
set_cell("A2", 3)
set_formula("B1", "A1 + A2")
set_formula("C1", "B1 * 2") # C1 depends on another formula cell
get_cell("C1") -> 16
set_cell("A1", 10)
get_cell("C1") -> 26
set_formula("A1", "C1 - 1")
get_cell("A1") -> error: circular reference A1 -> C1 -> B1 -> A1
Your design may instead reject the last set_formula call itself, if you check for cycles when a formula is written. State which you chose.
Before you code
Decide and state your assumptions on:
- Formula format: a string needing precedence and parentheses, or a pre-parsed structure? Are numeric literals allowed?
- What a reference to a never-set cell evaluates to (zero or an error).
- How division by zero is reported.
- Whether cycles are reported at write time or at read time.
- Whether
set_cellreplaces an existing formula in that cell and vice versa.
Part 1: Core operations
Implement the three methods for formulas whose operands are numbers and cells holding plain numbers. Cover precedence of the four operators, division by zero, malformed formulas, and overwriting a cell. Do not use eval on user input.
Part 2: Nesting, cycles and repeated references
Formulas may reference other formula cells to any depth. Detect and raise an error on circular references, both direct (A1 = A1 + 1) and indirect (A1 -> B1 -> C1 -> A1), and report the cycle. References that repeat without forming a cycle must keep working: a formula naming the same cell twice, or two cells reading one shared cell. A shared cell should not be recomputed needlessly within one read, and the spreadsheet should stay consistent after an error.
Part 3: Complexity and trade-offs
Analyze the cost of your design. Why compute values inside get_cell? Could the work move into the set operations? If writes are rare and reads frequent, which design fits better and what extra structures does it need?
Hints
Hint 1
Parse each formula once when it is set and keep only the list of referenced cell names plus an evaluable form (for example a small expression tree or reverse-Polish tokens). Write a tiny recursive-descent or shunting-yard parser instead of using eval.
Hint 2
For cycle detection use a depth-first evaluation with three states per cell: unvisited, in progress (on the current path), and done. Meeting an in-progress cell means a cycle; meeting a done cell is just a shared reference and must be reused, not flagged. Keep the path as a list so you can print A1 -> C1 -> B1 -> A1.
Hint 3
For the trade-off discussion, keep a forward map (cell to the cells it reads) and a reverse map (cell to the cells that read it). On any write, remove the cell's old edges from the reverse map before adding new ones, then invalidate cached values for everything reachable through the reverse map.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Formulas are strings with numbers, cell names,
+ - * /, parentheses and unary minus. Precedence is standard and operators are left-associative. - A never-set cell raises a
KeyError-style error (returning 0 is a one-line change, but silent zeros hide typos). - Division by zero raises
ZeroDivisionError. - Cycles are reported at read time in the baseline design. A write-time check is discussed in Part 3.
set_cellandset_formulaboth fully replace whatever the cell held.
Part 1: Parsing and the three operations
Tokenize with a regex such as \s*(\d+\.?\d*|[A-Za-z]+\d+|[-+*/()]). Anything left over is a malformed formula and raises ValueError. Parse with recursive descent:
expr -> term (('+'|'-') term)*term -> factor (('*'|'/') factor)*factor -> number | cell | '(' expr ')' | '-' factor
The parser produces a tuple tree such as ("+", ("ref","A1"), ("num",2)) and collects the set of referenced names. Parse at write time, so malformed input fails immediately and the cell is left untouched.
Part 2: Nesting and cycles
Evaluate with DFS and three states. visiting holds cells on the current path, done holds finished values for this read only.
import re
class Sheet:
def __init__(self):
self.cells = {} # name -> ("val", x) or ("f", tree, refs)
def set_cell(self, cell, value):
self.cells[cell] = ("val", value)
def set_formula(self, cell, formula):
tree, refs = _parse(formula) # raises ValueError if malformed
self.cells[cell] = ("f", tree, refs)
def get_cell(self, cell):
return self._eval(cell, [], {})
def _eval(self, name, path, memo):
if name in memo: # shared reference, not a cycle
return memo[name]
if name in path:
i = path.index(name)
raise RuntimeError("circular reference " + " -> ".join(path[i:] + [name]))
if name not in self.cells:
raise KeyError(f"unset cell {name}")
entry = self.cells[name]
if entry[0] == "val":
memo[name] = entry[1]
return memo[name]
path.append(name)
memo[name] = self._run(entry[1], path, memo)
path.pop()
return memo[name]
def _run(self, t, path, memo):
k = t[0]
if k == "num": return t[1]
if k == "ref": return self._eval(t[1], path, memo)
if k == "neg": return -self._run(t[1], path, memo)
a = self._run(t[1], path, memo)
b = self._run(t[2], path, memo)
if k == "+": return a + b
if k == "-": return a - b
if k == "*": return a * b
if b == 0: raise ZeroDivisionError("division by zero")
return a / b
Key points:
- The
pathlist (cells currently being evaluated) is what identifies a cycle. A cell that appears twice in a formula, or is shared by two branches, is found inmemo, not inpath, so there are no false positives. memois created per read, so a shared cell is computed once perget_cellcall.- Because state is local to the call and nothing is written to
self.cellsduring a read, an error leaves the sheet fully consistent. A cycle can be fixed by overwriting any cell on it. - Recursion depth equals the dependency chain length. For very deep chains use an explicit stack or raise the recursion limit.
Part 3: Complexity and trade-offs
Compute on read (above). Let R be the number of cells reachable from the queried cell and E the total references among them, plus formula token count.
set_cell/set_formula: O(1) plus parsing O(length of formula).get_cell: O(R + E) per call, thanks to per-read memoization. Without it, a diamond-shaped sheet can blow up exponentially.- Memory: only the cells and parsed trees.
This is simple and always correct, since there is no cache to go stale. It is the right default when reads are cheap or writes dominate.
Compute on write (eager). Keep a cached value per cell and a reverse map dependents[x] (cells whose formulas read x), plus the forward refs per cell.
- On a write to cell c: first remove c from
dependents[r]for each of its old refs r, then install the new refs and add c todependents[r]for each. This step is the most common bug: forgetting it leaves stale edges that cause wrong invalidation or phantom cycles. - Check for a cycle at write time: if c is reachable from any of its new refs by following forward edges (equivalently, a new ref is reachable from c through
dependents), reject the write and restore the old definition. This gives fail-fast behavior and keeps the stored graph always acyclic. - Recompute c and everything downstream in topological order (or DFS with memo) over the reverse map. Cost is O(affected cells + their edges).
get_cellbecomes O(1).
Lazy cache with invalidation is a middle path: on write, only mark downstream cells dirty through the reverse map (O(affected)); on read, recompute dirty cells on demand and cache the result. Repeated reads of unchanged cells are O(1), and writes that touch cells nobody reads cost almost nothing.
Choice. With rare writes and frequent reads, use a persistent cache with reverse dependencies: pay O(affected) per write and O(1) per read. The cost is extra memory (two maps plus cached values) and the invalidation logic, which must handle three triggers: a value change, a formula change (old edges removed, new edges added), and a cell being overwritten from formula to plain value (old edges removed). With frequent writes to hub cells that have thousands of dependents, eager recomputation wastes work, so prefer the lazy-dirty variant. Division-by-zero and unset-cell errors should be cached or recomputed consistently, so that fixing the offending cell invalidates dependents correctly.
Common mistakes
- Using
eval, which is both a security hole and a precedence trap. - Flagging any previously visited cell as a cycle, which rejects legal diamonds like
B1 = A1 + A1. - Marking cells visited globally without removing them from the current path, which gives the opposite error and misses real cycles.
- Mutating cached values mid-evaluation so a failed read leaves half-updated state.
- Not cleaning reverse edges when a formula is replaced.
- Integer vs float division: decide whether
7 / 2is3.5and document it.
Testing checklist
Direct self-reference, a 3-cell cycle, a diamond (shared cell), the same cell twice in one formula, overwriting a formula with a number, overwriting a formula with different refs and checking old dependents no longer trigger recomputation, division by zero, unset reference, malformed input, and a chain of a few thousand cells.