KatInterview

Design a Spreadsheet Data Model with Dependent Cell Evaluation

Data Structure DesignModel answer
MediumModel answerData Structure DesignData Structure DesignGraphCaching

Last 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

  1. 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).
  2. 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.
  3. Dependency Graph Management: Maintain relationships between cells to enable efficient propagation of changes.
  4. 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.
  5. 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).