In-Memory Spreadsheet Engine with Formulas and Cycle Handling
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Design an in-memory spreadsheet engine over a grid of cells and expose it through:
def spreadsheet_operations(
operations: List[str], arguments: List[List]
) -> List[Optional[int]]:
Every cell coordinate consists of one uppercase column letter 'A' through 'Z' followed immediately by a 1-based row number 1 through 1000 (such as 'A1', 'D15', or 'Z1000'). Any cell that has never been written holds 0 by default.
Process the commands in operations alongside their matching parameter lists in arguments, returning a list with one result per command:
-
"SET"with[cell, value]- Store literal integer
valueinsidecell, discarding any prior number or formula stored there. - Propagate the change to every cell whose formula depends on
celldirectly or through intermediate cells. - Return
value.
- Store literal integer
-
"GET"with[cell]- Return the current evaluated integer value of
cell(orNoneifcellis currently in an error state caused by a circular dependency).
- Return the current evaluated integer value of
-
"SUM"with[cell, refs]- Store a live sum formula in
cell(replacing any prior number or formula) over the reference strings inrefs. - Each element of
refsis either a single coordinate (such as'B2') or an inclusive rectangular block'X1:Y2'covering every column between'X'and'Y'and every row between1and2. - If a cell appears multiple times across
refs(either listed repeatedly or covered by overlapping blocks), include its value once per occurrence. An emptyrefslist evaluates to0. - Propagate the updated result to downstream dependent cells and return
cell's evaluated total (orNoneon a cycle).
- Store a live sum formula in
Dependency & Cycle Semantics
- Overwriting a formula cell via
"SET"or a new"SUM"removes its old incoming dependencies so changes to previously referenced cells no longer affect it. - If a
"SUM"command introduces a circular reference loop (for example, a cell referencing itself, orA2referencingB2whileB2referencesA2), the new formula is still stored incell. Every cell on a cycle — and every cell whose formula directly or transitively reads a cyclic cell — evaluates toNone. If a later"SET"or"SUM"breaks the cycle, affected cells automatically recover valid integer values. - Keep
"GET"fast rather than re-walking large unchanged dependency chains from scratch on every read.
Examples
Example 1
Input:
operations = ["SET", "SET", "SUM", "SET", "SUM", "SET", "GET", "GET"]
arguments = [
["A1", 3],
["B2", 4],
["C1", ["A1:B2", "B2"]],
["C1", 10],
["D1", ["C1", "A1"]],
["A1", 6],
["C1"],
["D1"]
]
Output:
[3, 4, 11, 10, 13, 6, 10, 16]
Walk-through: After A1 = 3 and B2 = 4, SUM("C1", ["A1:B2", "B2"]) adds the four cells in A1:B2 (3 + 0 + 0 + 4 = 7) plus the extra "B2" (4) to produce 11. Next, SET("C1", 10) overwrites C1's formula with the plain integer 10, and SUM("D1", ["C1", "A1"]) evaluates to 10 + 3 = 13. When A1 changes to 6, C1 stays 10 because its formula was replaced, while D1 updates to 10 + 6 = 16.
Example 2
Input:
operations = ["SET", "SUM", "SUM", "SET", "GET"]
arguments = [
["B1", 5],
["B2", ["B1"]],
["B3", ["B1:B2"]],
["B1", -2],
["B3"]
]
Output:
[5, 5, 10, -2, -4]
Walk-through: Initially B1 = 5, B2 = 5, and B3 = B1 + B2 = 10. Updating B1 to -2 cascades through B2 (-2) into B3 (-2 + -2 = -4).
Example 3
Input:
operations = ["GET", "SUM", "GET"]
arguments = [["Z999"], ["M10", []], ["M10"]]
Output:
[0, 0, 0]
Walk-through: Reading an untouched cell (Z999) yields 0, and summing an empty list of references ([]) also evaluates to 0.
Example 4
Input:
operations = ["SET", "SUM", "SUM", "GET", "SET", "GET"]
arguments = [
["A2", 7],
["B2", ["A2"]],
["A2", ["B2"]],
["B2"],
["A2", 9],
["B2"]
]
Output:
[7, 7, None, None, 9, 9]
Walk-through: Defining A2 = SUM(["B2"]) while B2 = SUM(["A2"]) forms a two-cell loop, so both A2 and B2 become None. Later, SET("A2", 9) replaces A2's formula with literal 9, breaking the loop so B2 recovers to 9.
Constraints
- Column identifiers are single uppercase ASCII letters
'A'through'Z'(26columns). - Row identifiers are integers
1through1000(1,000rows, up to26,000cells total). len(operations) == len(arguments)- Cell values set via
"SET"are signed integers (positive, zero, or negative). - Every coordinate in
argumentsand insiderefslies within'A1'..'Z1000'.
Step-by-step walkthrough
Understand the operations and rules
We need to build an in-memory spreadsheet over columns
'A'through'Z'and rows1through1000(26,000 possible cells such as'A1','B2', and'Z1000'). The judge callsspreadsheet_operations(operations, arguments)and expects one return value per operation:SET(cell, value): store plain integervalueincell, erasing any previous value or formula there, and returnvalue.GET(cell): return the current evaluated value ofcell.SUM(cell, refs): store a live sum formula incelloverrefs(where each item is a single cell'B2'or a rectangular range'A1:B2'), and return its evaluated value.
Looking closely at the examples reveals three important rules:
- Unset cells equal
0: Example 3 showsGET('Z999') == 0andSUM('M10', []) == 0. - Duplicate references add multiple times: In Example 1 (
A1 = 3,B2 = 4),SUM('C1', ['A1:B2', 'B2'])returns11, becauseB2appears once inside'A1:B2'and a second time explicitly (3 + 0 + 0 + 4 + 4 = 11). - Cycles store the formula and evaluate to
None: In Example 4 (A2 = 7,B2 = SUM(['A2'])), callingSUM('A2', ['B2'])returnsNone, andGET('B2')afterward also returnsNone. WhenSET('A2', 9)later breaks the loop,B2automatically recovers to9.
Why evaluating from scratch on every GET falls short
The simplest idea is to store raw formulas and recursively evaluate a cell's references every time
GETis called. That breaks down in three ways:- Repeated work: In a long chain
A1 -> A2 -> ... -> Z1000, everyGET('Z1000')walks all 26,000 cells again even when nothing changed, making reads painfully slow. - Stack overflow: A 26,000-cell chain is far deeper than Python's default recursion limit (~1,000 frames) and raises
RecursionError. - Infinite loops on cycles: If
A2sumsB2andB2sumsA2, naive recursion bounces back and forth forever.
- Repeated work: In a long chain
Key idea: reverse dependencies and topological recalculation
Instead of recomputing on
GET, we keep every cell's evaluated value cached soGETis an instant O(1) dictionary lookup. WheneverSETorSUMmodifies a cellstart, we recompute onlystartand the cells whose formulas depend onstart(directly or through a chain).To find those downstream cells quickly, we store edges in both directions:
formulas[cell]: whatcellreads ({ref_cell: multiplicity}).dependents[ref]: which formula cells readref(reverse edges / subscribers).
Be careful about the order in which we recompute affected cells! Look at this diamond-shaped graph when
A1changes:A1 (changed!) / \ v \ B1 | \ | v v C1 --> D1 = C1 + A1If we simply recomputed cells in breadth-first order from
A1,D1is 1 hop fromA1whileC1is 2 hops (A1 -> B1 -> C1), soD1would be recomputed beforeC1got its new value!We solve both evaluation order and cycle detection at once with Kahn's topological sort restricted to the
affectedset:- Collect
affected: Followdependentsarrows starting atstartto gather every cell reachable downstream. - Count
waiting[cell]: For each cell inaffected, count how many of its distinct formula references are also inaffected(references outsideaffecteddid not change, so their cached values are already up to date). - Process ready cells (
waiting == 0): Pop a ready cell from a queue, compute its new value from its references, and decrementwaitingon each of its affected dependents — pushing any dependent whosewaitinghits0. - Spot cycles (
waiting > 0left over): Cells in a cycle wait on each other in a loop, so theirwaitingcounts never hit0(and neither do cells waiting on that cycle). Setting every leftover cell withwaiting[cell] > 0toNonecatches all cycles automatically!
Parse cell coordinates and expand ranges
A cell ID like
'B12'has a single uppercase column letter (cell_id[0]) followed by an integer row (int(cell_id[1:])). A range'A1:B2'expands across every column code from'A'to'B'and every row from1to2.In
expand_refs, we accumulate{cell: count}rather than a plain set. That way,['A1:B1', 'B1']becomes{'A1': 1, 'B1': 2}:B1's value is multiplied by2during evaluation, while we only store one reverse edge per distinct cell!from collections import deque def parse_cell(cell_id: str) -> Tuple[str, int]: """Split `'B12'` into its column letter `'B'` and integer row `12`.""" col_letter = cell_id[0] row_number = int(cell_id[1:]) return col_letter, row_number def cells_in_range(first: str, last: str) -> List[str]: """List every cell ID inside the inclusive rectangle between `first` and `last`.""" first_col, first_row = parse_cell(first) last_col, last_row = parse_cell(last) # Using min/max handles ranges even if corners are given in non-top-left order start_col_ord = ord(min(first_col, last_col)) end_col_ord = ord(max(first_col, last_col)) start_row = min(first_row, last_row) end_row = max(first_row, last_row) cells: List[str] = [] for col_ord in range(start_col_ord, end_col_ord + 1): col_letter = chr(col_ord) for row_num in range(start_row, end_row + 1): cells.append(f"{col_letter}{row_num}") return cells def expand_refs(refs: List[str]) -> Dict[str, int]: """Count how many times each cell is referenced across `refs`, expanding `'A1:B2'` ranges.""" # counts: Dict[str, int] — e.g. ['A1:B1', 'B1'] -> {'A1': 1, 'B1': 2} counts: Dict[str, int] = {} for ref in refs: if ":" in ref: first, last = ref.split(":") expanded = cells_in_range(first, last) else: expanded = [ref] for cell in expanded: counts[cell] = counts.get(cell, 0) + 1 return countsStore spreadsheet state and handle SET, GET, and SUM
Whenever
SETorSUMwrites tocell,_clear_formula(cell)must first detachcellfrom thedependentssets of its old formula references. Otherwise, as seen in Example 1 whenSET('C1', 10)replacesC1's old formula, changingA1later would mistakenly wake upC1!In
_evaluate(cell), ifcellhas no formula it simply returnsself.values.get(cell, 0). Otherwise it sumsref_value * countacross its references — returningNoneimmediately if any referenced cell currently holdsNone(an upstream cycle error).class Spreadsheet: def __init__(self) -> None: # values: Dict[str, Optional[int]] — cached value per cell, e.g. {'A1': 10, 'B1': None}; unset -> 0 self.values: Dict[str, Optional[int]] = {} # formulas: Dict[str, Dict[str, int]] — formula cell -> {ref_cell: count}, e.g. {'C1': {'A1': 1, 'B2': 2}} self.formulas: Dict[str, Dict[str, int]] = {} # dependents: Dict[str, Set[str]] — reverse edges: cell -> formula cells that directly reference it self.dependents: Dict[str, Set[str]] = {} def set_cell(self, cell: str, number: int) -> int: # Overwriting a cell must first remove any old formula and its reverse dependency edges self._clear_formula(cell) self.values[cell] = number self._recalculate(cell) return number def get_cell(self, cell: str) -> Optional[int]: # Missing keys were never set and default to 0; explicitly stored `None` (cycle error) is preserved return self.values.get(cell, 0) def sum_cells(self, cell: str, refs: List[str]) -> Optional[int]: self._clear_formula(cell) ref_counts = expand_refs(refs) self.formulas[cell] = ref_counts # Register reverse edges so changes to any `ref` notify `cell` for ref in ref_counts: if ref not in self.dependents: self.dependents[ref] = set() self.dependents[ref].add(cell) self._recalculate(cell) return self.values[cell] def _clear_formula(self, cell: str) -> None: """Remove `cell`'s existing formula and detach `cell` from its old references' subscriber sets.""" if cell not in self.formulas: return for old_ref in self.formulas[cell]: self.dependents[old_ref].discard(cell) del self.formulas[cell] def _evaluate(self, cell: str) -> Optional[int]: """Compute `cell`'s value once from the already-updated values of its direct references.""" if cell not in self.formulas: return self.values.get(cell, 0) total = 0 for ref, count in self.formulas[cell].items(): ref_value = self.values.get(ref, 0) # If any referenced cell has a cycle error (`None`), that error propagates to `cell` if ref_value is None: return None total += ref_value * count return totalRecalculate affected cells with Kahn's algorithm
Now we translate our 4-phase recalculation plan directly into iterative loops (no recursion, so 26,000-cell chains never hit a stack limit):
def _recalculate(self, start: str) -> None: """Incrementally recompute `start` and all cells downstream of it in topological order.""" # Phase 1: walk reverse edges (`dependents`) to collect `start` and all transitive dependents affected: Set[str] = {start} stack: List[str] = [start] while stack: current = stack.pop() for dep in self.dependents.get(current, ()): if dep not in affected: affected.add(dep) stack.append(dep) # Phase 2: for each affected cell, count how many distinct affected cells its formula waits on # (references outside `affected` did not change, so their cached values are already valid) # ready: FIFO queue of affected cell IDs whose waiting count has reached 0 waiting: Dict[str, int] = {} ready = deque() for cell in affected: in_degree = 0 for ref in self.formulas.get(cell, {}): if ref in affected: in_degree += 1 waiting[cell] = in_degree if in_degree == 0: ready.append(cell) # Phase 3: Kahn's topological sort — evaluate a cell only after all affected inputs are ready while ready: cell = ready.popleft() self.values[cell] = self._evaluate(cell) for dep in self.dependents.get(cell, ()): if dep in affected: waiting[dep] -= 1 if waiting[dep] == 0: ready.append(dep) # Phase 4: any affected cell whose `waiting` count never reached 0 is on or downstream of a cycle for cell in affected: if waiting[cell] > 0: self.values[cell] = NoneTrace through Example 4 (cycle creation and recovery)
Let's trace Example 4 (
SET('A2', 7),SUM('B2', ['A2']),SUM('A2', ['B2']),GET('B2'),SET('A2', 9),GET('B2')):1. SET('A2', 7) affected = {'A2'}, waiting = {'A2': 0}, ready = ['A2'] -> values['A2'] = 7 2. SUM('B2', ['A2']) dependents['A2'] = {'B2'} affected = {'B2'}, waiting = {'B2': 0} ('A2' is NOT in affected, its cached 7 is valid!) -> values['B2'] = 7 3. SUM('A2', ['B2']) (closes cycle A2 <-> B2) dependents['B2'] = {'A2'}, dependents['A2'] = {'B2'} affected = {'A2', 'B2'} waiting = {'A2': 1, 'B2': 1}, ready = [] (neither is 0!) Phase 4 sets both stuck cells to None -> values['A2'] = None, values['B2'] = None 4. GET('B2') -> returns values['B2'] = None 5. SET('A2', 9) (breaks the cycle!) _clear_formula('A2') detaches 'A2' from dependents['B2']; dependents['A2'] still has {'B2'} affected = {'A2', 'B2'} waiting = {'A2': 0, 'B2': 1}, ready = ['A2'] Pop 'A2' -> values['A2'] = 9, decrements waiting['B2'] to 0 -> push 'B2' Pop 'B2' -> values['B2'] = 9 (both cells recover!) 6. GET('B2') -> returns values['B2'] = 9Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def parse_cell(cell_id: str) -> Tuple[str, int]: """Split `'B12'` into its column letter `'B'` and integer row `12`.""" col_letter = cell_id[0] row_number = int(cell_id[1:]) return col_letter, row_number def cells_in_range(first: str, last: str) -> List[str]: """List every cell ID inside the inclusive rectangle between `first` and `last`.""" first_col, first_row = parse_cell(first) last_col, last_row = parse_cell(last) # Using min/max handles ranges even if corners are given in non-top-left order start_col_ord = ord(min(first_col, last_col)) end_col_ord = ord(max(first_col, last_col)) start_row = min(first_row, last_row) end_row = max(first_row, last_row) cells: List[str] = [] for col_ord in range(start_col_ord, end_col_ord + 1): col_letter = chr(col_ord) for row_num in range(start_row, end_row + 1): cells.append(f"{col_letter}{row_num}") return cells def expand_refs(refs: List[str]) -> Dict[str, int]: """Count how many times each cell is referenced across `refs`, expanding `'A1:B2'` ranges.""" # counts: Dict[str, int] — e.g. ['A1:B1', 'B1'] -> {'A1': 1, 'B1': 2} counts: Dict[str, int] = {} for ref in refs: if ":" in ref: first, last = ref.split(":") expanded = cells_in_range(first, last) else: expanded = [ref] for cell in expanded: counts[cell] = counts.get(cell, 0) + 1 return counts class Spreadsheet: """In-memory spreadsheet with eager incremental recalculation so `GET` is O(1). Cycle behavior: A `SUM` that introduces a cycle is still stored (overwriting the cell's old value/formula). Every cell on a cycle — and every cell whose formula transitively depends on a cycle — evaluates to `None`. If a later `SET` or `SUM` breaks the cycle, affected cells recover their numeric values automatically. """ def __init__(self) -> None: # values: Dict[str, Optional[int]] — cached value per cell, e.g. {'A1': 10, 'B1': None}; unset -> 0 self.values: Dict[str, Optional[int]] = {} # formulas: Dict[str, Dict[str, int]] — formula cell -> {ref_cell: count}, e.g. {'C1': {'A1': 1, 'B2': 2}} self.formulas: Dict[str, Dict[str, int]] = {} # dependents: Dict[str, Set[str]] — reverse edges: cell -> formula cells that directly reference it self.dependents: Dict[str, Set[str]] = {} def set_cell(self, cell: str, number: int) -> int: # Overwriting a cell must first remove any old formula and its reverse dependency edges self._clear_formula(cell) self.values[cell] = number self._recalculate(cell) return number def get_cell(self, cell: str) -> Optional[int]: # Missing keys were never set and default to 0; explicitly stored `None` (cycle error) is preserved return self.values.get(cell, 0) def sum_cells(self, cell: str, refs: List[str]) -> Optional[int]: self._clear_formula(cell) ref_counts = expand_refs(refs) self.formulas[cell] = ref_counts # Register reverse edges so changes to any `ref` notify `cell` for ref in ref_counts: if ref not in self.dependents: self.dependents[ref] = set() self.dependents[ref].add(cell) self._recalculate(cell) return self.values[cell] def _clear_formula(self, cell: str) -> None: """Remove `cell`'s existing formula and detach `cell` from its old references' subscriber sets.""" if cell not in self.formulas: return for old_ref in self.formulas[cell]: self.dependents[old_ref].discard(cell) del self.formulas[cell] def _evaluate(self, cell: str) -> Optional[int]: """Compute `cell`'s value once from the already-updated values of its direct references.""" if cell not in self.formulas: return self.values.get(cell, 0) total = 0 for ref, count in self.formulas[cell].items(): ref_value = self.values.get(ref, 0) # If any referenced cell has a cycle error (`None`), that error propagates to `cell` if ref_value is None: return None total += ref_value * count return total def _recalculate(self, start: str) -> None: """Incrementally recompute `start` and all cells downstream of it in topological order.""" # Phase 1: walk reverse edges (`dependents`) to collect `start` and all transitive dependents affected: Set[str] = {start} stack: List[str] = [start] while stack: current = stack.pop() for dep in self.dependents.get(current, ()): if dep not in affected: affected.add(dep) stack.append(dep) # Phase 2: for each affected cell, count how many distinct affected cells its formula waits on # (references outside `affected` did not change, so their cached values are already valid) # ready: FIFO queue of affected cell IDs whose waiting count has reached 0 waiting: Dict[str, int] = {} ready = deque() for cell in affected: in_degree = 0 for ref in self.formulas.get(cell, {}): if ref in affected: in_degree += 1 waiting[cell] = in_degree if in_degree == 0: ready.append(cell) # Phase 3: Kahn's topological sort — evaluate a cell only after all affected inputs are ready while ready: cell = ready.popleft() self.values[cell] = self._evaluate(cell) for dep in self.dependents.get(cell, ()): if dep in affected: waiting[dep] -= 1 if waiting[dep] == 0: ready.append(dep) # Phase 4: any affected cell whose `waiting` count never reached 0 is on or downstream of a cycle for cell in affected: if waiting[cell] > 0: self.values[cell] = None def spreadsheet_operations(operations: List[str], arguments: List[List]) -> List[Optional[int]]: sheet = Spreadsheet() results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "SET": results.append(sheet.set_cell(args[0], args[1])) elif op == "GET": results.append(sheet.get_cell(args[0])) elif op == "SUM": results.append(sheet.sum_cells(args[0], args[1])) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of the spreadsheet as a subscriber notification network — a directed graph (a collection of nodes connected by one-way arrows) where every cell keeps a subscriber list (dependents) of the formulas that read it. Whenever a cell changes via SET or SUM, it notifies all downstream subscribers. However, if cell D1 adds B1 + C1 and both B1 and C1 depend on A1, D1 must wait at the intersection until both B1 and C1 finish updating before computing its new sum. We enforce that rule with Kahn's algorithm — a queue-based topological sort (ordering nodes so every prerequisite comes before the nodes that use it) that tracks each affected cell's in-degree (how many affected inputs it is still waiting on) and evaluates a cell only when its wait count drops to 0. Better yet, cells trapped in a circular loop wait on each other forever, so their wait counts never hit 0 — exposing cycles automatically!
Evaluating formulas on demand during every GET fails because a 26,000-cell chain forces each GET to re-walk thousands of unchanged cells, overflows Python's recursion stack, and spins forever on cycles unless visited-path state is tracked. Conversely, pushing updates with a plain breadth-first search without waiting counts fails on diamond dependencies (A1 -> B1 -> C1 and D1 = A1 + C1), where D1 sits 1 hop from A1 and would read C1's stale value before C1 updates at hop 2.
Let's trace Example 2 (B1 -> B2 -> B3):
SET('B1', 5):affected = {'B1'},waiting['B1'] = 0->values['B1'] = 5.SUM('B2', ['B1']):B2subscribes toB1.affected = {'B2'}(B1did not change, sowaiting['B2'] = 0) ->values['B2'] = 5.SUM('B3', ['B1:B2']):B3subscribes toB1andB2->values['B3'] = 5 + 5 = 10.SET('B1', -2): following subscribers fromB1gathersaffected = {'B1', 'B2', 'B3'}withwaiting = {'B1': 0, 'B2': 1, 'B3': 2}.B1evaluates first (-2), droppingB2to0andB3to1; thenB2evaluates (-2), droppingB3to0; finallyB3evaluates (-2 + -2 = -4). Every laterGETis an instant dictionary lookup!
Complexity
Let A be the number of affected cells on an update (start plus its transitive dependents, meaning cells that depend on start directly or through intermediate formulas), F be the total number of distinct formula references across those A affected cells, L be the expanded cell count of refs in a SUM call (with duplicates), and P be the number of distinct references in any old formula overwritten on the target cell.
GET: O(1) time. Every cell's latest evaluated value (orNoneon a cycle) is kept cached inself.values, soGETdoes a single hash-map lookup.SET: O(P + A + F) time. Clearing an overwritten formula removesPreverse edges in O(P); then collectingaffected, countingwaiting, and running Kahn's queue each touch theAaffected cells and theirFformula edges a constant number of times.SUM: O(P + L + A + F) time. Expanding ranges visitsLcell coordinates, registering reverse edges takes at most O(L), and_recalculateruns in O(A + F).- Space: O(C + E), where
Cis the number of cells written so far andEis the total number of distinct(formula_cell, referenced_cell)links stored once inself.formulasand once inself.dependents(plus O(A) temporary sets/queues during_recalculate).
Edge cases
- Unset cells and empty formulas:
GET('Z999')andSUM('M10', [])both evaluate to0because unset keys default to0viaself.values.get(cell, 0). - Duplicate and overlapping references (
['A1:B2', 'B2']): storing{cell: count}multipliesB2's value by2in_evaluatewhile adding'C1'todependents['B2']once. - Self-loops (
SUM('A1', ['A1'])orSUM('B2', ['A1:C3'])):waitingstarts at1on that single cell,readyis empty, and Phase 4 marks itNone. - Existing dependents of a newly formed cycle: if
C1 = B1 + B1already existed beforeA1 <-> B1became a cycle,C1is part ofaffected, never reacheswaiting == 0, and turns intoNonetoo. - Partial and full cycle recovery: overwriting a cycle cell with
SET(or a non-cyclicSUM) detaches the cyclic edge and runs_recalculate, restoring valid numbers to cells no longer downstream of any cycle while keeping cells on a separate remaining loop atNone. - Overwriting a formula (
SETafterSUM, orSUMafterSUM):_clear_formularemoves olddependentsentries so changes to previously referenced cells no longer trigger updates.
Common mistakes
- Rejecting a cyclic
SUMand keeping the previous value: Example 4 expectsSUM('A2', ['B2'])and the subsequentGET('B2')to returnNone, not the old value7. - Storing formula references as a
setinstead of{cell: count}: loses duplicate occurrences insiderefsand returns7instead of11on Example 1's['A1:B2', 'B2']. - Forgetting to remove reverse edges when overwriting a cell: leaves ghost entries in
self.dependents, causing overwrittenSETcells or updatedSUMcells to be wrongly recalculated later. - Recomputing affected cells in plain BFS/DFS discovery order: evaluates downstream merge nodes in a diamond graph before all upstream branches have been updated, caching stale totals.
- Using
self.values.get(cell) or 0: in PythonNone or 0evaluates to0! You must checkif ref_value is None:explicitly so cycle errors (None) are not silently turned into0.
Alternative approaches
- Lazy evaluation with dirty flags: Instead of recomputing values eagerly on every
SET/SUM, markstartand its transitive dependents with a dirty flag (a boolean marker recording that a cached value is out of date, stopping traversal whenever an already-dirty cell is hit). ThenGET(cell)evaluates dirty cells on demand using an iterative depth-first stack with a "currently on path" set to detect cycles, caching clean results for futureGETs. Lazy invalidation shines when manySETs happen back-to-back before a singleGET, at the cost of slower and more statefulGETcalls.
Follow-up questions
- How would your implementation change if a SUM command that creates a circular reference had to be rejected without modifying the sheet? Before mutating
cell's formula insum_cells, collectaffected(all cells that currently depend oncell, includingcellitself) by walkingself.dependentsfromcell. A new formula oncellcreates a cycle if and only if at least one of its expanded references is inaffected(meaningrefalready depends oncell, socell -> refwould close a loop). If anyref in affected, returnNone(or raise an exception) immediately without touchingself.formulas,self.dependents, orself.values. - Under what workload patterns would lazy dirty-bit invalidation outperform eager topological recalculation? Eager recalculation excels when reads (
GET/ UI renders) outnumber writes or when every edit immediately re-renders all visible dependent cells anyway. Lazy dirty-bit marking wins during bulk imports or batch scripts that execute thousands ofSETcalls before reading a few summary cells — marking an already-dirty subgraph stops in O(1) instead of recomputing the same downstream totals thousands of times. - How could you optimize formulas spanning huge rectangular blocks like B1:Z1000 when individual cells inside the block change frequently? Expanding
'B1:Z1000'creates 25,000 reverse edges and scans 25,000 entries per evaluation. Instead, maintain a 2D Fenwick tree (a compact grid data structure that updates one cell and sums any rectangular subgrid in O(log R * log C) time — roughly5 * 10 = 50operations on a26 x 1000sheet) for numeric cell values, plus a second 2D Fenwick tree counting how many cells currently holdNoneso any error inside the rectangle still evaluates toNone, while storing range objects unexpanded rather than per-cell edges.
Follow-up questions
- How would your implementation change if a SUM command that creates a circular reference had to be rejected without modifying the sheet?
- Under what workload patterns would lazy dirty-bit invalidation outperform eager topological recalculation?
- How could you optimize formulas spanning huge rectangular blocks like B1:Z1000 when individual cells inside the block change frequently?
Similar questions
- Workout Tracking System with Live Trails and Leaderboards
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One