Eagerly Cached Cell Grid with Dependency Tracking
Data Structure DesignModel answerLast updated
Build a grid of cells that stores integers or sum formulas, keeps every value precomputed for constant-time reads, and refuses any write that would introduce a circular reference.
Task
Implement a small in-memory grid of cells. Each cell holds either a plain integer or a formula that adds up other cells. Reading a cell must take O(1) time, so every cell's value has to be computed ahead of time and stored. When a write changes a cell, every cell that depends on it, directly or indirectly, must be refreshed so no read ever returns stale data.
A write that would create a circular dependency must be rejected. In that case the grid must stay exactly as it was, and the call returns False.
Interface
class Spreadsheet:
def __init__(self):
...
def set_cell(self, cell_id: str, expression: str) -> bool:
...
def get_value(self, cell_id: str) -> int:
...
set_cell(cell_id, expression)
cell_idis a coordinate such as"A1"or"C3".expressionis one of:- an integer string such as
"42"or"-5", or - a formula starting with
"="followed by cell coordinates joined by"+", such as"=A1+B2"or"=C1".
- an integer string such as
- A reference to a cell that was never set counts as
0. - Returns
Trueif the write was applied. ReturnsFalse, with no change to any state, if the write would create a cycle (including a cell referencing itself).
get_value(cell_id)
- Returns the current stored integer for the cell, or
0if it was never set. - Must run in
O(1).
Examples
sheet = Spreadsheet()
sheet.set_cell("A1", "10")
sheet.set_cell("A2", "20")
sheet.set_cell("A3", "=A1+A2")
sheet.get_value("A3") # 30
sheet.set_cell("A1", "5")
sheet.get_value("A3") # 25
sheet = Spreadsheet()
sheet.set_cell("A1", "=B1")
sheet.set_cell("B1", "=C1")
sheet.set_cell("C1", "=A1") # False: A1 -> B1 -> C1 -> A1 would loop
sheet.set_cell("C1", "100")
sheet.get_value("A1") # 100
Constraints
- Cell IDs are alphanumeric, from
"A1"to"Z100". - Integer values lie in
[-10^9, 10^9]. - At most
2,000calls toset_celland100,000calls toget_value. - Formulas use only
+between cell references.
What to deliver
Explain your data structures and algorithm, argue why it is correct (including the rejected-write case), give time and space complexity, and write the code.
Hints
Hint 1
Think of the grid as a directed graph where an edge goes from a cell to every cell whose formula reads it. Store both the cells each formula references and the cells that read each cell.
Hint 2
When one cell is rewritten, only the edges coming into that cell change. So you can test for a cycle on the existing graph: the new references must not already be reachable from the cell by following 'is read by' edges.
Hint 3
Do the cycle test before changing anything, so a rejection needs no rollback. Then recompute the affected cells once each, in topological order, which a DFS finishing order (reversed) gives you. Keep a list, not a set, of references so that duplicates like =A1+A1 are counted twice.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the sheet as a directed acyclic graph (DAG). Draw an edge X -> Y when Y's formula reads X. Keep four dictionaries:
values[cell]: the cached integer.get_valueis one dictionary lookup, so it isO(1).literals[cell]: the raw number for cells that hold a plain integer.refs[cell]: the list of cells that this cell's formula reads. It is a list, so=A1+A1evaluates to2 * A1.dependents[cell]: the set of cells that read this cell (the forward edges).
Key observation
Rewriting cell X replaces only X's incoming edges (what X reads). The outgoing edges (who reads X) do not change. That simplifies both the cycle check and the recomputation.
Algorithm for set_cell(X, expr)
- Parse the expression into either an integer or a list of referenced cells
R. - Find the downstream set of X by running an iterative DFS from X over
dependentson the current graph. Record the finishing order and reverse it to get a topological order. X comes first. - Cycle check. The new edges are
r -> Xfor eachrinR. They close a loop exactly when someris already reachable from X, i.e. lies in the downstream set. This also catchesA1 = "=A1", because X is in its own downstream set. If so, returnFalsebefore any mutation. - Commit. Remove X from
dependents[old_r]for each old reference, add X todependents[r]for each new reference, and store the new literal or reference list. - Recompute every cell in the downstream order. Each cell reads only cells outside the downstream set (unchanged) or earlier in the order (already refreshed), so every cell is evaluated exactly once with fresh inputs.
Why it is correct
- Invariant: the graph is a DAG and every cached value equals its formula applied to current cached values.
- Rejection: the cycle check happens before any write to state, so a failed call leaves everything intact, including not creating entries for new cells.
- Acceptance: the topological order is computed on edges the update does not change. The new incoming edges come from cells outside the downstream set, so they cannot disturb that order. Cells outside the downstream set cannot depend on X, so their values remain valid.
Complexity
Let D be the downstream cells of X, E_D the edges among them, and k the length of the formula.
set_cell:O(k + |D| + E_D). The worst case isO(V + E)for the whole sheet, which is trivial for 2,000 writes.get_value:O(1).- Space:
O(V + E).
Code
from typing import Dict, List, Set
class Spreadsheet:
def __init__(self):
self.values: Dict[str, int] = {}
self.literals: Dict[str, int] = {}
self.refs: Dict[str, List[str]] = {}
self.dependents: Dict[str, Set[str]] = {}
def _parse(self, expression: str):
expr = expression.strip()
if expr.startswith("="):
refs = [t.strip() for t in expr[1:].split("+") if t.strip()]
return None, refs
return int(expr), []
def _downstream_topo(self, start: str):
visited = {start}
order: List[str] = []
stack = [(start, iter(self.dependents.get(start, ())))]
while stack:
node, it = stack[-1]
for nxt in it:
if nxt not in visited:
visited.add(nxt)
stack.append((nxt, iter(self.dependents.get(nxt, ()))))
break
else:
stack.pop()
order.append(node)
order.reverse()
return visited, order
def _evaluate(self, cell: str) -> int:
refs = self.refs.get(cell)
if refs:
return sum(self.values.get(r, 0) for r in refs)
return self.literals.get(cell, 0)
def set_cell(self, cell_id: str, expression: str) -> bool:
literal, new_refs = self._parse(expression)
downstream, order = self._downstream_topo(cell_id)
if any(r in downstream for r in new_refs):
return False
for r in set(self.refs.get(cell_id, ())):
deps = self.dependents.get(r)
if deps is not None:
deps.discard(cell_id)
for r in set(new_refs):
self.dependents.setdefault(r, set()).add(cell_id)
if literal is None:
self.refs[cell_id] = new_refs
self.literals.pop(cell_id, None)
else:
self.refs.pop(cell_id, None)
self.literals[cell_id] = literal
for cell in order:
self.values[cell] = self._evaluate(cell)
return True
def get_value(self, cell_id: str) -> int:
return self.values.get(cell_id, 0)
Trace of the cycle example
A1 = B1 and B1 = C1 create edges C1 -> B1 -> A1. Setting C1 = "=A1": the downstream set of C1 is {C1, B1, A1}, which contains the reference A1, so the call returns False. Setting C1 = "100" gives order [C1, B1, A1], so all three become 100.
Edge cases
- Unset references count as 0. Registering the reverse edge means a later write to that cell propagates correctly.
- Self-reference is rejected because X is in its own downstream set.
- Duplicate references keep a list for evaluation and a set for edges.
- Replacing a formula with a literal removes old incoming edges, then propagates to dependents.
- Negative numbers and whitespace are handled by
strip()andint(). - Deep chains of up to 2,000 cells can overflow Python's recursion limit, so the DFS is iterative.
Trade-offs and common mistakes
- Eager versus lazy: eager caching makes reads constant-time but makes writes touch the whole downstream set. Lazy evaluation with dirty flags flips this. With 2,000 writes against 100,000 reads, eager is the right choice.
- Mutate then roll back: this is error-prone. Checking first is simpler and safer.
- Recomputing by naive recursion: a cell reachable through many paths can be re-evaluated exponentially many times. A single pass in topological order evaluates each cell once.
- Storing only forward or only backward edges: you need the references to rewire edges and the dependents to propagate.
- Using a set for references: this silently turns
=A1+A1intoA1. - Running the cycle check on the graph after the update: it is simpler to ask whether any new reference is reachable from X in the old graph.