KatInterview

Live Spreadsheet with Eager Caching and Cycle Guards

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

Last updated

Build a spreadsheet engine where every write pre-computes all downstream values so reads are O(1) cache lookups, and circular definitions are rejected atomically.

Live Spreadsheet with Eager Caching and Cycle Guards

You are building a minimal in-memory spreadsheet engine. Cells can hold integer literals or arithmetic formulas that reference other cells. The engine must keep every cell's computed value pre-cached so that reads never traverse the dependency graph.

Implement live_sheet(operations: list[list[str]]) -> list[str].

Each operation is one of:

  • ["set", cell, raw] — define or redefine a cell.
  • ["get", cell] — retrieve a cell's current value.

Return one result string per operation, in order.


Return values

OperationResult
Successful set"OK"
Set that would create a circular dependency"CYCLE"
GetThe cell's value as a plain integer string, e.g. "0", "-3", "42" — no leading zeros, no leading + sign

Cell names and formula syntax

  • Cell names are one or more uppercase ASCII letters followed by a positive integer with no leading zeros — for example A1, Z99, AB10.
  • A raw value is either a signed integer literal (like "7" or "-3") or a formula string that begins with =.
  • Formula grammar: one or more terms joined by + or -. A term is either a non-negative integer constant or a cell reference. Spaces around tokens are allowed. Unary signs and parentheses do not appear inside formulas.
  • Examples of valid formulas: =A1+B2, =A1 + 3 - C5, =A1+A1.

Semantics

  • Unset cells evaluate to 0 and contribute 0 wherever referenced.
  • Repeated references count multiple times: =A1+A1 doubles A1's value.
  • A set replaces everything: the old definition, its value, and all its dependency edges are fully removed before the new ones are installed.
  • Cycle rejection is atomic: if the proposed new definition would introduce a direct or indirect cycle, the operation returns "CYCLE" and the entire sheet — every definition and every cached value — remains exactly as it was before the call.
  • Eager propagation: after any successful set, the engine immediately recomputes every cell that transitively depends on the changed cell. By the time the next operation is processed, all cached values are up to date.
  • Reads are O(1): get must return a stored integer — no graph traversal at read time.

Constraints

  • At most 500 operations total.
  • At most 100 terms per formula.
  • All cell names and raw strings are syntactically valid per the grammar above.
  • Every numeric value, including all intermediate sums during evaluation of an acyclic sheet, fits in a signed 32-bit integer.
  • The sheet starts completely empty.

Examples

Example 1

operations = [
  ["set", "A1", "2"],
  ["set", "B1", "=A1+1"],
  ["set", "C1", "=A1+B1"],
  ["set", "A1", "5"],
  ["get", "C1"]
]
result = ["OK", "OK", "OK", "OK", "11"]

When A1 changes from 2 to 5, B1 becomes 6 and C1 becomes 11. The get returns the already-cached value.

Example 2

operations = [
  ["set", "A1", "=B1"],
  ["set", "B1", "=A1+1"],
  ["get", "A1"],
  ["set", "A1", "3"],
  ["set", "B1", "=A1+1"],
  ["get", "B1"]
]
result = ["OK", "CYCLE", "0", "OK", "OK", "4"]

The second set tries to make B1 depend on A1, but A1 already depends on B1 — a cycle. The attempt is rejected and B1 stays unset (value 0). Later, redefining A1 as the literal 3 breaks the dependency that would have completed the cycle, so B1 = A1 + 1 = 4 is then accepted.


What is expected

  • A working implementation of live_sheet.
  • Correct cycle detection that never mutates the sheet on a rejected set.
  • Correct eager propagation in dependency order after every accepted set.
  • O(1) get, as described.
  • Clean handling of all edge cases: self-references, formula-to-literal rewrites, duplicate references within a formula, and unset cells.

Hints

Hint 1

Track two separate graph views: for each cell, the set of cells its formula reads from (inputs), and the set of cells whose formulas read from it (dependents). Updates travel along the dependents edges; cycle checks travel along the same edges in reverse.

Hint 2

Run the cycle check before touching anything. A new definition for cell X introduces edges X → r for each referenced cell r. A cycle exists if and only if X is already reachable from some r through the existing dependents graph — so DFS from X over dependents and see whether any r shows up.

Hint 3

After a successful set, collect all cells transitively reachable from X via dependents and recompute them in topological order using Kahn's algorithm. Count in-degrees using only edges inside the affected subgraph; cells outside it are already correct and can be read from the cache directly.