Live Spreadsheet with Eager Caching and Cycle Guards
Data Structure DesignModel answerLast 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
| Operation | Result |
|---|---|
| Successful set | "OK" |
| Set that would create a circular dependency | "CYCLE" |
| Get | The 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
0and contribute0wherever referenced. - Repeated references count multiple times:
=A1+A1doublesA1'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):
getmust 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core tension is between writes and reads: reads must be O(1), which means all computation must happen at write time. That forces an eager model — every set must propagate new values all the way through the dependency graph before returning.
Three sub-problems need to be solved cleanly:
- Cycle detection before any mutation.
- Atomic commit of the new definition.
- Ordered recomputation of everything downstream.
Data structures
Keep four dictionaries, all keyed by cell name:
terms[cell]— parsed formula as a list of(sign, ref_or_None, constant)tuples. A literal7becomes[(+1, None, 7)].refs[cell]— the set of distinct cell names the formula reads (deduplicated, for edge management).dependents[cell]— the set of cells that directly referencecell. This is the reverse graph.value[cell]— the cached computed integer.
Keeping terms and refs separate matters: terms preserves duplicates so arithmetic is correct (=A1+A1 counts twice), while refs contains each name once so in-degree counting during Kahn's algorithm doesn't double-count edges.
Phase 1 — cycle check
Before touching the sheet, DFS from X through dependents. This collects every cell that currently depends on X, directly or transitively. If any cell in new_refs appears in that reachable set (or equals X itself, covering self-references), the new definition would close a cycle. Return "CYCLE" immediately and leave everything untouched.
This works because the existing graph is acyclic by induction. The only way a cycle can form is through one of X's new outgoing edges, and the only way that edge closes a loop is if there is already a path from the target back to X — which is exactly what the DFS finds.
Phase 2 — commit
Only reached if no cycle was detected:
- For every cell in the old
refs[X], removeXfromdependents[old_ref]. - For every cell in
new_refs, addXtodependents[new_ref]. - Store
new_termsandnew_refs.
Phase 3 — eager recompute
Collect the affected set: X plus every cell reachable from X via dependents. Run Kahn's algorithm on this subgraph:
- In-degree of a node in the affected set = number of its formula inputs that are also in the affected set.
- Pop nodes with in-degree zero, evaluate them (reading cached values for inputs outside the affected set, which haven't changed), update their cache entry, and decrement neighbors.
This guarantees every cell is recomputed exactly once, in an order where all of its changed inputs are already final.
Edge cases
- Self-reference (
=A1+1while settingA1):A1 ∈ new_refsandA1is the start of the DFS, so it's indownstream. Caught immediately. - Formula → literal:
new_refsis empty. All old input edges are removed. Dependents still get recomputed. - Literal → formula: old edges are empty, new edges are added. Normal flow.
- Duplicate references (
=A1+A1):refsstoresA1once (correct edge count),termsstores it twice (correct arithmetic). - Unset cell read:
value.get(cell, 0)returns0. - Output format:
str(int(...))produces canonical decimal with no leading zeros and a minus sign for negatives.
Complexity
| Operation | Time |
|---|---|
get | O(1) |
set (cycle check) | O(V + E) where V, E are nodes/edges reachable from X |
set (recompute) | O(V + E + T) where T is total terms in affected cells |
| Space | O(total formula terms + cells) |
With at most 500 operations and 100 terms per formula, the worst case is around 500 × 50,000 elementary steps — negligible in practice.
Common mistakes
- Mutating before the cycle check passes. If you unlink old edges first and the check then fails, you've corrupted the graph. Always check before touching anything.
- Topological sort over the whole graph instead of just the affected subgraph. Correct but wasteful, and easy to get wrong when some cells have no stored terms.
- Counting duplicate references in in-degrees. Use
refs(deduplicated) for graph structure; useterms(with duplicates) only for evaluating the sum. - Forgetting that an unset cell evaluates to 0. A cell that is referenced but never written has no entry in
value;value.get(ref, 0)handles this.
Python implementation
import re
from collections import deque
from typing import List
_TERM_RE = re.compile(r'([+-]?)([A-Z]+[0-9]+|[0-9]+)')
def live_sheet(operations: List[List[str]]) -> List[str]:
terms = {} # cell -> list of (sign: int, ref: str|None, const: int)
refs = {} # cell -> set of distinct referenced cell names
dependents = {} # cell -> set of cells whose formula mentions cell
value = {} # cell -> cached int
def parse(raw: str):
raw = raw.strip()
if not raw.startswith('='):
return [(1, None, int(raw))]
expr = raw[1:].replace(' ', '').replace('\t', '')
result = []
for sign_str, tok in _TERM_RE.findall(expr):
sign = -1 if sign_str == '-' else 1
if tok[0].isalpha():
result.append((sign, tok, 0))
else:
result.append((sign, None, int(tok)))
return result
def evaluate(cell: str) -> int:
total = 0
for sign, ref, const in terms.get(cell, []):
total += sign * (value.get(ref, 0) if ref is not None else const)
return total
def reachable_via_dependents(start: str):
"""All cells reachable from start through the dependents graph,
including start itself."""
seen = {start}
stack = [start]
while stack:
cur = stack.pop()
for d in dependents.get(cur, ()):
if d not in seen:
seen.add(d)
stack.append(d)
return seen
results = []
for op in operations:
if op[0] == 'get':
results.append(str(value.get(op[1], 0)))
continue
cell, raw = op[1], op[2]
new_terms = parse(raw)
new_refs = {ref for _, ref, _ in new_terms if ref is not None}
# --- Phase 1: cycle check (read-only) ---
downstream = reachable_via_dependents(cell)
if any(r in downstream for r in new_refs):
results.append('CYCLE')
continue
# --- Phase 2: commit ---
# Unlink old dependency edges.
for r in refs.get(cell, ()):
dependents.setdefault(r, set()).discard(cell)
# Link new dependency edges.
for r in new_refs:
dependents.setdefault(r, set()).add(cell)
terms[cell] = new_terms
refs[cell] = new_refs
# --- Phase 3: eager recompute in topological order ---
affected = reachable_via_dependents(cell)
# Build in-degrees within the affected subgraph only.
indegree = {c: 0 for c in affected}
for c in affected:
for r in refs.get(c, ()):
if r in affected:
indegree[c] += 1
queue = deque(c for c in affected if indegree[c] == 0)
while queue:
cur = queue.popleft()
value[cur] = evaluate(cur)
for d in dependents.get(cur, ()):
if d in affected:
indegree[d] -= 1
if indegree[d] == 0:
queue.append(d)
results.append('OK')
return results