Design a Spreadsheet Data Model with Dependent Cell Evaluation
Data Structure DesignModel answerLast updated
Design the internal data structures and API for a spreadsheet engine supporting raw inputs, computed values, dependency tracking, and formula evaluation.
Design an in-memory data engine for an interactive spreadsheet application that supports displaying both the raw input of a cell and its calculated output.
A cell's raw content can either be a static scalar value (like a number or string) or a formula that references one or more other cells (e.g., =A1 + B2). When a cell's formula or value changes, all downstream dependent cells must update correctly.
Context and Requirements
- Dual Representation: The engine must store the exact raw input entered by the user while exposing a computed view (the evaluated result or an error state).
- Dynamic Updates: If a cell is updated—whether changing a literal value to a formula, replacing a formula with a literal, or modifying an existing formula—all affected dependent cells must be updated or invalidated.
- Dependency Graph Management: Maintain relationships between cells to enable efficient propagation of changes.
- Cycle Detection: Detect circular references (e.g., cell A relies on cell B, which relies on cell A) and mark affected cells with a circular reference error rather than crashing or entering infinite loops.
- API Operations: Define and implement an engine interface that supports:
- Setting a cell's content by coordinate.
- Fetching a cell's raw string/input.
- Fetching a cell's computed display value.
System Scope
Focus on the single-user, in-memory object model, dependency graph algorithms, and evaluation flow. Assume a basic expression parser is available or write a lightweight parser for basic arithmetic (e.g., +, -, cell references).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architectural Design
To support efficient spreadsheet operations, we separate the system into three main components:
- Cell Data Structure: Holds the raw user input, parsed AST/references, cached evaluation result, and graph edges.
- Dependency Graph (Directed Graph): Manages edges between cells ($A \to B$ means $B$ depends on $A$).
- Spreadsheet Engine: Exposes the public API (
set_cell,get_raw,get_value), handles topological evaluation, and performs cycle detection.
+---------------------------------------------+
| Spreadsheet Engine |
+---------------------------------------------+
| |
v v
+-------------------+ +-------------------+
| Cell Model | <--- References ->| Dependency Graph |
| - Raw String | | - Direct Dependencies
| - Cached Value | | (Cells I read) |
| - Computed Status | | - Reverse Dependents
+-------------------+ | (Cells reading me)
+-------------------+
Data Models & Class Definitions
1. Cell State and Representation
A cell can hold either a literal value or a formula. We retain the exact raw user string for presentation purposes (get_raw).
from enum import Enum
from typing import Union, List, Set, Dict, Optional
class CellType(Enum):
LITERAL = 1
FORMULA = 2
class ValueType(Enum):
NUMBER = 1
STRING = 2
ERROR = 3
class CellValue:
def __init__(self, val_type: ValueType, val: Union[float, str]):
self.val_type = val_type
self.val = val
def __repr__(self):
return f"CellValue({self.val_type.name}, {self.val})"
class Cell:
def __init__(self, cell_id: str):
self.cell_id: str = cell_id
self.raw_input: str = ""
self.cell_type: CellType = CellType.LITERAL
# Parsed elements
self.dependencies: Set[str] = set() # References that THIS cell depends on
self.dependents: Set[str] = set() # Cells that depend on THIS cell
# Cached result
self.cached_value: Optional[CellValue] = CellValue(ValueType.STRING, "")
self.is_dirty: bool = False
Dependency Management & Cycle Detection
When updating cell $X$:
- Parse Expression: Extract all cell references $Y_1, Y_2, \dots$ from the raw string.
- Update Edges:
- Remove stale reverse edges: for each $Y \in \text{old_dependencies}(X)$, remove $X$ from $Y.\text{dependents}$.
- Add new reverse edges: for each $Y \in \text{new_dependencies}(X)$, add $X$ to $Y.\text{dependents}$.
- Check for Cycles: Perform a cycle detection run using standard Depth-First Search (DFS) with 3-color node marking (
UNVISITED,VISITING,VISITED). - Invalidate and Re-evaluate: Mark $X$ and all downstream transitive dependents as dirty, then evaluate them in topological order.
Implementation
import re
class Spreadsheet:
def __init__(self):
self.cells: Dict[str, Cell] = {}
def _get_or_create_cell(self, cell_id: str) -> Cell:
if cell_id not in self.cells:
self.cells[cell_id] = Cell(cell_id)
return self.cells[cell_id]
def _parse_formula(self, formula: str) -> List[str]:
"""Extracts cell identifiers (e.g., A1, B12) from formula string."""
if not formula.startswith("="):
return []
# Basic regex to extract uppercase alphanumeric tokens representing cell coordinates
tokens = re.findall(r'\b[A-Z]+[0-9]+\b', formula)
return list(set(tokens))
def set_cell(self, cell_id: str, content: str) -> None:
cell = self._get_or_create_cell(cell_id)
cell.raw_input = content
# Determine cell type and parse dependencies
old_dependencies = set(cell.dependencies)
if content.startswith("="):
cell.cell_type = CellType.FORMULA
new_dependencies = set(self._parse_formula(content))
else:
cell.cell_type = CellType.LITERAL
new_dependencies = set()
# Update forward graph edges for this cell
cell.dependencies = new_dependencies
# Update reverse graph edges for dependencies
removed_deps = old_dependencies - new_dependencies
added_deps = new_dependencies - old_dependencies
for dep_id in removed_deps:
if dep_id in self.cells:
self.cells[dep_id].dependents.discard(cell_id)
for dep_id in added_deps:
dep_cell = self._get_or_create_cell(dep_id)
dep_cell.dependents.add(cell_id)
# Re-evaluate dirty propagation chain
self._propagate_and_evaluate(cell_id)
def get_raw(self, cell_id: str) -> str:
if cell_id in self.cells:
return self.cells[cell_id].raw_input
return ""
def get_value(self, cell_id: str) -> CellValue:
cell = self._get_or_create_cell(cell_id)
return cell.cached_value
def _has_cycle(self, start_id: str) -> bool:
"""DFS Cycle Detection using node states: 0=UNVISITED, 1=VISITING, 2=VISITED."""
state = {}
def dfs(node_id: str) -> bool:
state[node_id] = 1 # VISITING
node = self.cells.get(node_id)
if node:
for dep in node.dependencies:
dep_state = state.get(dep, 0)
if dep_state == 1:
return True # Cycle detected
if dep_state == 0:
if dfs(dep):
return True
state[node_id] = 2 # VISITED
return False
return dfs(start_id)
def _propagate_and_evaluate(self, target_id: str) -> None:
# Step 1: Collect all affected cells (target + downstream dependents)
affected: Set[str] = set()
queue = [target_id]
while queue:
curr_id = queue.pop(0)
if curr_id not in affected:
affected.add(curr_id)
curr_cell = self.cells.get(curr_id)
if curr_cell:
queue.extend(list(curr_cell.dependents))
# Step 2: Compute topological sort order for affected cells
in_degree = {cid: 0 for cid in affected}
for cid in affected:
cell = self.cells[cid]
for dep in cell.dependencies:
if dep in affected:
in_degree[cid] += 1
topo_order = []
zero_in_degree = [cid for cid, deg in in_degree.items() if deg == 0]
while zero_in_degree:
curr_id = zero_in_degree.pop(0)
topo_order.append(curr_id)
curr_cell = self.cells.get(curr_id)
if curr_cell:
for neighbor in curr_cell.dependents:
if neighbor in in_degree:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
zero_in_degree.append(neighbor)
# Cycle check: if topo_order doesn't contain all affected cells, a cycle exists
has_cycle_globally = len(topo_order) < len(affected)
# Step 3: Evaluate cells in topological order
for cid in topo_order:
self._evaluate_single_cell(self.cells[cid], has_cycle_globally)
# Handle nodes involved in cycles
if has_cycle_globally:
unresolved = affected - set(topo_order)
for cid in unresolved:
self.cells[cid].cached_value = CellValue(ValueType.ERROR, "#REF!")
def _evaluate_single_cell(self, cell: Cell, global_cycle_flag: bool) -> None:
if self._has_cycle(cell.cell_id):
cell.cached_value = CellValue(ValueType.ERROR, "#REF!")
return
if cell.cell_type == CellType.LITERAL:
try:
val = float(cell.raw_input)
cell.cached_value = CellValue(ValueType.NUMBER, val)
except ValueError:
cell.cached_value = CellValue(ValueType.STRING, cell.raw_input)
return
# Simple formula evaluator for addition/subtraction
expr = cell.raw_input[1:] # strip '='
# Substitute cell references with evaluated numbers
for dep_id in cell.dependencies:
dep_val = self.get_value(dep_id)
if dep_val.val_type == ValueType.ERROR:
cell.cached_value = CellValue(ValueType.ERROR, "#VALUE!")
return
elif dep_val.val_type == ValueType.NUMBER:
expr = re.sub(r'\b' + dep_id + r'\b', str(dep_val.val), expr)
else:
cell.cached_value = CellValue(ValueType.ERROR, "#VALUE!")
return
try:
# Safe evaluation for basic arithmetic expressions
result = eval(expr, {"__builtins__": None}, {})
cell.cached_value = CellValue(ValueType.NUMBER, float(result))
except Exception:
cell.cached_value = CellValue(ValueType.ERROR, "#EVAL_ERR")
Complexity Analysis
| Operation | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
get_raw | $O(1)$ | $O(1)$ | Direct dictionary lookup. |
get_value | $O(1)$ | $O(1)$ | Returns pre-computed/cached result. |
set_cell | $O(V + E)$ | $O(V + E)$ | $V$ is the number of affected downstream cells, $E$ is the number of dependency edges. Runs topological sort and updates affected nodes. |
Trade-offs & Design Considerations
-
Eager vs. Lazy Evaluation:
- Eager (Implemented): Updates happen during
set_cell. Reads (get_value) are $O(1)$. Ideal for interactive spreadsheets where UI components require instantaneous read latency. - Lazy: Re-evaluates cells only when
get_valueis requested. Saves computation on frequent batch cell writes, but introduces variable latencies during read requests.
- Eager (Implemented): Updates happen during
-
Error Propagation Policy:
- When cell $A$ contains an error (
#REF!or#VALUE!), any dependent cell $B$ referencing $A$ propagates#VALUE!upward, preventing unhandled exceptions.
- When cell $A$ contains an error (
-
Memory Footprint:
- Double adjacency lists (
dependenciesanddependents) accelerate graph traversal at the expense of doubling edge storage requirements.
- Double adjacency lists (