Design a Formula Engine with Cycle Detection
Data Structure DesignModel answerLast updated
Build a computation system where cells hold values or formulas referencing other cells, detecting circular dependencies before they corrupt state.
Design and implement a computational engine that manages cells containing either direct numeric values or formulas that reference other cells. Each formula performs addition on two referenced cells (format: "X1 + Y2").
Your engine must maintain consistency: when any cell's value changes, all cells that transitively depend on it must reflect the updated result. Before accepting any new formula, verify it won't introduce a circular dependency—if it would, reject the operation entirely and leave all state unchanged.
Interface:
Provide a class with these operations:
set_value(cell: str, value: float): Assign a numeric value directly to a cellset_formula(cell: str, formula: str): Define a cell as the sum of two others (e.g.,"A1 + B2")get_value(cell: str) -> float: Retrieve the current computed result for a cell
Behavior:
- Cell identifiers follow the pattern
[Letter][Number](e.g.,"A1","Z99") - Formulas accept only the exact format
"[Cell1] + [Cell2]"with optional whitespace - A cell that has never been assigned defaults to
0.0 - Circular dependencies must trigger an error before modifying any state
Example:
engine = Engine()
engine.set_value("A1", 10.0)
engine.set_value("B1", 20.0)
engine.set_formula("C1", "A1 + B1")
engine.get_value("C1") # → 30.0
engine.set_value("A1", 5.0)
engine.get_value("C1") # → 25.0 (automatically updated)
Circular Dependency Example:
engine.set_formula("A1", "B1 + C1") # A1 reads B1
engine.set_formula("B1", "A1 + D1") # error: B1 would read A1, creating A1→B1→A1
Handle transitive dependencies correctly—a change to A1 should cascade through all formulas that depend on it, directly or indirectly.
Hints
Hint 1
Model the relationships between cells as a directed graph where edges represent 'reads from' dependencies
Hint 2
Before adding a formula's edges, verify the source cell isn't already reachable from either of its new dependencies
Hint 3
Cache computed values and only recompute the affected subgraph in topological order when an upstream cell changes
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem requires building a dependency-tracking computation graph with two critical properties: fast reads via caching, and guaranteed acyclicity through proactive validation.
Core Design Decisions
1. Graph Representation
Track two adjacency structures:
- precedents[C]: the set of cells that C reads from (its formula operands)
- dependents[C]: the set of cells that read from C (formulas that reference C)
For C1 = A1 + B1, this creates:
- precedents[C1] = {A1, B1}
- dependents[A1].add(C1), dependents[B1].add(C1)
2. Push vs. Pull Evaluation
This solution uses eager push: cache every cell's computed value, and when a cell changes, immediately recompute all downstream dependents in topological order. This trades write cost for O(1) reads—appropriate when reads vastly outnumber writes, which is typical for spreadsheets.
Alternative (lazy pull): recompute on-demand during get_value by recursively evaluating precedents. Simpler but incurs cost on every read and requires memoization to avoid exponential blowup in diamonds.
3. Validate-Before-Mutate
In set_formula, perform the full cycle check before modifying any graph edges or formulas. If rejected, the engine's state remains exactly as it was—no partial updates, no cleanup needed.
Cycle Detection Algorithm
A new formula X = P + Q introduces edges P → X and Q → X. This creates a cycle if and only if X is already reachable from P or Q in the current graph (via the dependents direction).
Why this is sufficient:
- The existing graph is acyclic (inductive invariant).
- Any new cycle must use at least one new edge (P→X or Q→X).
- Such a cycle exists ⟺ a path X → … → P (or X → … → Q) already exists.
- Self-reference (
X = X + Y) is caught as the degenerate case where X ∈ {X, Y}.
Implementation: Run DFS from X along dependents edges. If we encounter P or Q, reject. Iterative DFS prevents stack overflow on deep chains.
Example: After A1 = B1 + C1, attempting B1 = A1 + D1 would create B1→A1→B1. The DFS from B1 visits A1 (via existing dependent edge), sees A1 is a new precedent, and raises an error.
Propagation After Updates
When a cell X changes (via set_value or set_formula):
- Find affected region: DFS from X along dependents edges to collect all transitively downstream cells.
- Order them topologically: Use post-order DFS (visit node after all children) then reverse. This ensures each cell is recomputed after all its precedents within the affected subgraph.
- Recompute in order: Evaluate formulas using cached values. Precedents outside the affected region are unchanged, so their cached values remain valid.
Why this handles transitive dependencies: Consider A1 → B1 → C1 → D1. Changing A1 collects {B1, C1, D1} in topological order. B1 reads the new A1, C1 reads the updated B1, D1 reads the updated C1. Each computation sees the correct precedent values because the order guarantees it.
Complexity
Let V = total cells, E = total edges, D = downstream cells from a changed cell, E_D = edges among them.
| Operation | Time | Space |
|---|---|---|
| get_value | O(1) | O(1) |
| set_value | O(D + E_D) | O(D) |
| set_formula | O(D + E_D) | O(D) |
Graph storage is O(V + E). All traversals use explicit stacks (O(D) space), avoiding Python's recursion limit even for deeply nested formulas.
Edge Cases and Contract Choices
- Unset cells default to 0.0: Matches spreadsheet semantics. Formula
C1 = A1 + B1works even if A1 and B1 were never set. - Self-reference:
A1 = A1 + B1is rejected as a cycle. - Duplicate operands:
C1 = A1 + A1is allowed; evaluates to2 * A1. The set representation naturally deduplicates edges. - Overwriting formulas: Replacing a formula clears old precedent edges before adding new ones. Otherwise, stale cells would incorrectly update the overwritten cell.
- Formula syntax: Accept whitespace-padded formulas. Reject malformed input like
"A1+"or"A1 + B2 + C3"with ValueError. - Failed operations: If
set_formuladetects a cycle, raise CircularDependencyError (ValueError subclass) without modifying any state—no cleanup phase needed.
Implementation Sketch
import re
from collections import defaultdict
class CircularDependencyError(ValueError):
pass
class Engine:
def __init__(self):
self.values = {} # cell -> cached value
self.formulas = {} # cell -> (left, right)
self.precedents = defaultdict(set) # cell -> set of cells it reads
self.dependents = defaultdict(set) # cell -> set of cells reading it
self._cell_pattern = re.compile(r'^[A-Z][0-9]+$')
def set_value(self, cell: str, value: float):
cell = self._validate(cell)
self._remove_formula(cell)
self.values[cell] = float(value)
self._update_downstream(cell)
def set_formula(self, cell: str, formula: str):
cell = self._validate(cell)
left, right = self._parse_formula(formula)
# Check for cycle before mutating
if self._would_create_cycle(cell, {left, right}):
raise CircularDependencyError(
f"Formula {formula!r} for {cell} would create a cycle"
)
self._remove_formula(cell)
self.formulas[cell] = (left, right)
for operand in (left, right):
self.precedents[cell].add(operand)
self.dependents[operand].add(cell)
self.values[cell] = self._compute(cell)
self._update_downstream(cell)
def get_value(self, cell: str) -> float:
cell = self._validate(cell)
return self.values.get(cell, 0.0)
def _validate(self, cell: str) -> str:
cell = cell.strip()
if not self._cell_pattern.match(cell):
raise ValueError(f"Invalid cell: {cell!r}")
return cell
def _parse_formula(self, formula: str):
parts = formula.split('+')
if len(parts) != 2:
raise ValueError(f"Invalid formula: {formula!r}")
return self._validate(parts[0]), self._validate(parts[1])
def _remove_formula(self, cell: str):
if cell in self.formulas:
for p in self.precedents[cell]:
self.dependents[p].discard(cell)
self.precedents[cell].clear()
del self.formulas[cell]
def _compute(self, cell: str) -> float:
left, right = self.formulas[cell]
return self.values.get(left, 0.0) + self.values.get(right, 0.0)
def _would_create_cycle(self, start: str, targets: set) -> bool:
# DFS from start along dependents; if we hit any target, cycle exists
stack, visited = [start], {start}
while stack:
node = stack.pop()
if node in targets:
return True
for child in self.dependents[node]:
if child not in visited:
visited.add(child)
stack.append(child)
return False
def _update_downstream(self, cell: str):
# Collect downstream in topological order, then recompute
order = []
visited = {cell}
stack = [(cell, iter(self.dependents[cell]))]
while stack:
node, children = stack[-1]
try:
child = next(children)
if child not in visited:
visited.add(child)
stack.append((child, iter(self.dependents[child])))
except StopIteration:
stack.pop()
if node != cell:
order.append(node)
for node in order:
if node in self.formulas:
self.values[node] = self._compute(node)
This approach maintains correctness through careful ordering, detects cycles before corruption, and delivers O(1) reads at the cost of O(affected subgraph) writes—the right tradeoff for spreadsheet workloads.