In-Memory Grid with Formula Evaluation and Cycle Guards
Data Structure DesignModel answerLast updated
Build a spreadsheet class in three stages: plain integer cells, formula parsing with dependency-order evaluation, then cycle detection and targeted recomputation.
In-Memory Grid with Formula Evaluation and Cycle Guards
You are building a lightweight in-memory grid that supports both plain values and computed cells. Implement it in three stages, finishing and verifying each one before moving on — the full scope is substantial for a single interview, and a working Part 1 is worth more than a half-finished Part 3.
Cells are identified by a label: one uppercase letter followed by one or more digits (e.g. A1, C12). The class exposes exactly two methods:
class Grid:
def set_cell(self, label: str, value) -> None: ...
def get_cell(self, label: str) -> int | None: ...
Clarifying questions worth raising before you start
- Single-letter columns only, or also multi-letter ones like
AA3? - Is
a1the same cell asA1, or are labels case-sensitive? - Can a cell be overwritten with a different type (number → formula or vice versa)?
- Can values or formula results be negative?
Part 1 — Plain integer cells
set_cell(label, value) stores an integer. get_cell(label) returns it. No formulas yet.
Cover:
- A keyed storage structure and a clear return value for a label that has never been set.
- Basic label validation if the interviewer asks for it.
- Speed: this part should take only a few minutes.
Part 2 — Formula cells
set_cell now also accepts a formula string beginning with =, for example:
set_cell("A1", "=B1+C1+1")— sum of two cells and a constantset_cell("A1", "=1+2")— formula with no cell references
get_cell always returns a pre-computed integer (O(1)). Recomputing every stored cell on each write is acceptable here. No circular references will occur in this stage.
Clarifying questions for this part:
- Which operators are supported — just
+, or also-,*, and parentheses? - If a formula references a cell that has never been set, is that cell treated as
0or does the formula itself becomeNone/an error? - Can formulas contain whitespace? How should a malformed formula be reported?
Cover:
- Parsing a formula string into cell references and integer literals.
- Evaluating cells in a correct dependency order so that chains like
A1 = B1 + 1,B1 = C1 + 1produce the right answer. - A single consistent rule for never-set cells (both direct reads and formula references).
- An honest discussion of the write cost of recomputing everything.
Part 3 — Cycle detection and selective recomputation
Formulas may now form cycles, e.g. set_cell("A1", "=B1") then set_cell("B1", "=A1+1"). Your implementation must:
- Detect cycles before committing any state change, including self-references like
set_cell("A1", "=A1+1"). - Recompute only affected cells — those that transitively depend on the cell that just changed — rather than the whole grid.
Clarifying questions for this part:
- Should a cycle-creating call be rejected (sheet unchanged) or accepted with the involved cells marked as errors?
- Is a self-reference a cycle?
Cover:
- A forward-dependency and reverse-dependency graph that stays consistent when a formula is replaced or a cell is changed back to a plain number.
- A traversal that finds the topological evaluation order for just the affected subgraph.
- How
set_cellandget_cellcomplexity changes from Part 2 to Part 3.
Hints
Hint 1
For Part 2, store three things per cell: the raw input, the set of cell labels it references, and the last computed value. That structure extends cleanly into Part 3 without a rewrite.
Hint 2
Correct evaluation order in Part 2 and Part 3 is a topological sort of the dependency graph. In Part 2 you can run it over all cells; in Part 3 run it only over the transitive dependents of the changed cell (found by following reverse-dependency edges).
Hint 3
Cycle detection in Part 3 is a DFS from the newly referenced cells: if you can reach the cell being written before finishing the DFS, the write would form a cycle and should be rejected before any state is mutated.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and design
The key insight is to keep one data model throughout all three parts and extend it incrementally rather than rewriting:
cells[label] = {
"raw": <int or formula string>,
"refs": <set of labels this cell reads from>,
"value": <last computed int, or None>
}
A second structure arrives in Part 3: rdeps[label] — the set of labels whose formulas read from label. This reverse-dependency map is what makes targeted recomputation possible.
Part 1 — Plain integer cells
Straightforward: a dict keyed by label, None for missing cells.
class Grid:
def __init__(self):
self._cells = {} # label -> {"raw", "refs", "value"}
def set_cell(self, label: str, value) -> None:
self._cells[label] = {"raw": value, "refs": set(), "value": int(value)}
def get_cell(self, label: str) -> int | None:
entry = self._cells.get(label)
return entry["value"] if entry else None
Complexity: O(1) read and write. Finish this in under five minutes and move on.
Part 2 — Formula cells
Parsing. Split the formula on + (extend to -/* with a proper tokeniser if the interviewer asks). Classify each token as a cell reference (matches /^[A-Z]+\d+$/) or an integer literal.
Evaluation order. Build a dependency graph from the refs sets and run a topological sort (Kahn's algorithm or DFS post-order) over all stored cells. Evaluate in that order so upstream values are ready before downstream cells consume them.
Never-set rule. Treat a missing cell as 0 inside a formula (simpler) or propagate None (stricter). Pick one, state it, and apply it consistently to direct get_cell calls too.
import re
from collections import defaultdict, deque
class Grid:
def __init__(self):
self._cells = {}
# ── helpers ──────────────────────────────────────────────
_LABEL = re.compile(r'^[A-Z]+\d+$')
def _parse(self, formula: str):
"""Return (tokens, refs) for a '=...' string."""
tokens = re.split(r'(\+)', formula[1:]) # extend for -/* as needed
refs = {t.strip() for t in tokens
if self._LABEL.match(t.strip())}
return formula[1:], refs
def _topo_order(self):
"""Kahn's topological sort over all cells."""
in_deg = {lbl: 0 for lbl in self._cells}
children = defaultdict(set) # label -> labels that depend on it
for lbl, meta in self._cells.items():
for ref in meta["refs"]:
if ref in self._cells:
children[ref].add(lbl)
in_deg[lbl] += 1
queue = deque(lbl for lbl, d in in_deg.items() if d == 0)
order = []
while queue:
lbl = queue.popleft()
order.append(lbl)
for child in children[lbl]:
in_deg[child] -= 1
if in_deg[child] == 0:
queue.append(child)
return order
def _eval_expr(self, expr: str) -> int | None:
"""Evaluate a tokenised expression with current cell values."""
tokens = re.split(r'(\+)', expr)
result = 0
for t in tokens:
t = t.strip()
if t == '+':
continue
if self._LABEL.match(t):
v = self.get_cell(t)
if v is None:
return None # or use 0 — state your policy
result += v
else:
result += int(t)
return result
# ── public API ────────────────────────────────────────────
def set_cell(self, label: str, value) -> None:
if isinstance(value, str) and value.startswith("="):
expr, refs = self._parse(value)
self._cells[label] = {"raw": value, "refs": refs, "value": None}
else:
self._cells[label] = {"raw": value, "refs": set(), "value": int(value)}
# recompute everything in dependency order
for lbl in self._topo_order():
meta = self._cells[lbl]
if meta["refs"]: # it's a formula cell
meta["value"] = self._eval_expr(
self._cells[lbl]["raw"][1:]
)
def get_cell(self, label: str) -> int | None:
entry = self._cells.get(label)
return entry["value"] if entry else None
Complexity — Part 2. set_cell is O(N + E) where N is the number of stored cells and E is the total number of references. get_cell is O(1). The recompute-everything approach is simple but scales poorly for large grids with infrequent changes.
Part 3 — Cycle detection and targeted recomputation
Cycle detection. Before mutating any state, run a DFS starting from every cell referenced by the new formula. If the DFS can reach the label being written, the new assignment would form a cycle — reject it and leave the grid unchanged.
Reverse-dependency map. Maintain rdeps[label] = set of cells whose formulas read from label. Update this map whenever a cell's refs change (remove old refs, add new ones).
Targeted recomputation. On a valid set_cell, find the transitive closure of rdeps starting from label — these are the only cells whose cached values may have changed. Run a topological sort on that subgraph and recompute only those cells in order.
def set_cell(self, label: str, value) -> None:
# --- parse new refs ---
if isinstance(value, str) and value.startswith("="):
_, new_refs = self._parse(value)
else:
new_refs = set()
# --- cycle check (DFS from new_refs, must not reach label) ---
visited = set()
stack = list(new_refs)
while stack:
node = stack.pop()
if node == label:
raise ValueError(f"Cycle detected: setting {label} would create a cycle")
if node not in visited:
visited.add(node)
meta = self._cells.get(node)
if meta:
stack.extend(meta["refs"])
# --- update rdeps ---
old_refs = self._cells.get(label, {}).get("refs", set())
for ref in old_refs - new_refs:
self._rdeps[ref].discard(label)
for ref in new_refs - old_refs:
self._rdeps[ref].add(label)
# --- store cell ---
raw = value
self._cells[label] = {"raw": raw, "refs": new_refs, "value":
int(value) if not new_refs else None}
# --- recompute transitive dependents only ---
affected = self._transitive_dependents(label)
for lbl in self._topo_order_subset({label} | affected):
meta = self._cells[lbl]
if meta["refs"]:
meta["value"] = self._eval_expr(meta["raw"][1:])
elif lbl == label and not new_refs:
meta["value"] = int(value)
Complexity — Part 3. set_cell is O(D + E_D) where D is the number of transitive dependents and E_D the edges among them — much better than O(N + E) when changes affect a small part of the grid. get_cell remains O(1).
Common mistakes
- Forgetting to clean up rdeps when a formula is replaced: old reverse-dependency edges linger and cause phantom recomputations.
- Running cycle detection after mutating state: if you store the new refs first and then detect a cycle, rolling back is messy. Always check before writing.
- Inconsistent None handling: treating a missing cell as
0in one place andNonein another produces subtle bugs in formula chains. - Not handling self-references:
set_cell("A1", "=A1+1")needs to be caught by the cycle check — the DFS start set should include the new refs, and reaching the written label at any depth (including depth 0 if the cell references itself) is a cycle.