KatInterview

Design a Formula Engine with Cycle Detection

Data Structure DesignModel answer
MediumModel answerData Structure Designgraphstopological-sortcycle-detection

Last 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 cell
  • set_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