In-Memory Cell Grid with Formula Chaining
Data Structure DesignAuto-graded · 23 test casesLast updated
Tests dependency graph design, lazy cache invalidation, recursive formula evaluation, and cycle detection in a grid of named cells.
In-Memory Cell Grid with Formula Chaining
You are building a minimal in-memory grid engine. Each cell in the grid has a string address: one uppercase letter (A–Z) for the column and an integer (1–1000) for the row, e.g. A1, B2, Z1000.
A cell holds either a plain integer or a derived formula (the sum of other cells). Uninitialized cells have the value 0.
Operations
Your engine must process a sequence of operations given as two parallel lists:
operations: a list of strings, each one of"SET","GET", or"SUM".arguments: a list of argument lists, one per operation.
Return a list of results, one per operation, in order.
SET
Arguments: [address, number]
Assigns the integer number to the cell at address. Any formula previously stored there is discarded, and all dependency edges from that cell are removed.
Returns: the integer that was just stored.
GET
Arguments: [address]
Returns the current integer value of the cell at address.
- If the cell holds a plain integer, return it directly.
- If the cell holds a formula, evaluate it recursively: a formula cell's value is the sum of the current values of every cell it references (with duplicates counted separately, uninitialized cells contributing
0). - If evaluation encounters a cycle (directly or transitively), return
null/Nonefor every cell involved in or depending on that cycle.
Returns: an integer, or null/None if the cell is part of a cycle.
SUM
Arguments: [address, refs]
Stores a summation formula in the cell at address. refs is a list of reference strings. Each reference is either:
- A single address, e.g.
"B2", or - A rectangular range
"X1:Y2", representing every cell whose column is betweenXandY(inclusive) and whose row is between the two row numbers (inclusive). Column and row bounds may appear in either order, e.g."B2:A1"is valid and covers the same cells as"A1:B2".
Duplicates within refs (or produced by overlapping ranges) are not deduplicated — each occurrence contributes its value separately to the sum.
Any formula or value previously stored in address is replaced.
Returns: the evaluated sum of the new formula (using the same rules as GET, including None for cycles).
Behavioral contract
- Invalidation: after any
SETorSUMoperation on a cell, all cells whose formulas depend (directly or transitively) on that cell must reflect the change on the nextGETorSUMcall. - Formula replacement: a
SETon a formula cell removes the formula. ASUMon a cell that held a plain value removes that value. In both cases the old dependency edges are cleaned up. - Cycle behavior: a cycle is permitted to be stored; it is not rejected at write time. Evaluating any cell that lies on a cycle, or that transitively depends on one, yields
None. If a subsequent update breaks the cycle, the affected cells return to normal integer values. - Empty refs:
SUMwith an emptyrefslist is valid; the cell evaluates to0.
Constraints
1 <= total operations <= 1000- Column letters are in
A–Z(single character only). - Row numbers are integers in
1–1000. - Integer values passed to
SETfit in a standard 32-bit signed integer. - Each range in
refsexpands to at most 26 × 1000 = 26 000 cells. refsmay be an empty list.- Cycles may be introduced at any point in the sequence.
Examples
Example 1
Input: spreadsheet_operations(['SET', 'SET', 'SUM', 'SUM', 'SET', 'GET', 'SUM', 'SET', 'GET'], [['A1', 1], ['B2', 2], ['C1', ['A1:B2', 'B2']], ['C1', ['B2']], ['C1', 5], ['C1'], ['D1', ['C1', 'A1']], ['A1', 10], ['C1']])
Output: [1, 2, 5, 2, 5, 5, 6, 10, 5]
Example 2
Input: spreadsheet_operations(['SET', 'SUM', 'GET', 'SET', 'GET'], [['A1', 3], ['B1', ['A1']], ['B1'], ['A1', 8], ['B1']])
Output: [3, 3, 3, 8, 8]
Example 3
Input: spreadsheet_operations(['GET', 'SUM', 'GET'], [['Z1000'], ['A1', []], ['A1']])
Output: [0, 0, 0]
Example 4
Input: spreadsheet_operations(['SET', 'SUM', 'SUM', 'GET'], [['A1', 4], ['B1', ['A1']], ['A1', ['B1']], ['A1']])
Output: [4, 4, None, None]
Hints
Hint 1
Keep plain values and formula definitions in separate maps. When a cell is overwritten, make sure you remove its old outgoing dependency edges before adding new ones — otherwise stale edges will corrupt future evaluations.
Hint 2
Rather than recomputing every formula cell on every write, just mark the written cell and all its transitive dependents as 'dirty' (invalidate the cache). On a GET, evaluate recursively but return the cached value immediately if the cache is still fresh.
Hint 3
To detect cycles during evaluation, thread a 'currently visiting' set through the recursion. If you arrive at a cell that is already in that set, you have found a back edge — return None and let it propagate up. Cache the None so repeat calls don't re-traverse the cycle.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is to separate storage from evaluation and pay for recomputation lazily — only when a stale cell is actually read.
Data structures
Four dictionaries drive everything:
values— maps a cell address to a plain integer (written bySET).formulas— maps a cell address to its expanded list of dependency addresses (written bySUM). Ranges are flattened here once at write time, and duplicates are deliberately preserved.reverse— maps each cell to the set of formula cells that directly reference it. This is the inverted dependency graph and is what makes targeted invalidation cheap.cache— maps a cell to its last known evaluated value. An absent entry means the cell is dirty and must be recomputed on the next read.
A cell holds either a plain value or a formula, never both. values and formulas are mutually exclusive for any given address at any given time.
Writing: SET and SUM
Before storing anything new, remove_formula deletes the cell's old outgoing edges from reverse. Without this step, a cell overwritten by SET would keep poisoning its former dependencies, and a SUM redefinition would accumulate stale edges.
After the new data is stored, invalidate does an iterative DFS over the reverse graph and evicts the cache entry of the changed cell and every cell that transitively depends on it. The seen set keeps this walk finite even in the presence of cycles.
Nothing is recomputed at write time — writes only mark affected regions dirty.
Reading: GET and the return value of SUM
evaluate is a recursive function. It checks the cache first: a hit returns immediately, keeping repeated reads O(1). On a miss it recurses into each dependency, accumulates the sum, stores the result in the cache, and returns.
Why the three behavioral rules hold
Duplicates count separately. formulas stores the expanded list, not a set. If B2 appears twice, evaluate adds its value twice.
SET removes a formula. remove_formula is called before writing to values, so the old edges vanish and A1 no longer influences the overwritten cell.
Propagation is correct. invalidate walks every transitive dependent. A subsequent GET on any of those cells finds no cache entry and recomputes from scratch, picking up the new value.
Cycle detection
evaluate carries a visiting set containing every cell currently on the Python call stack. Arriving at a cell that is already in visiting means a back edge exists — a cycle. The function returns None, which propagates up through every frame in the current recursion path. Each frame caches its None before returning, so repeat reads on cyclic cells are O(1).
None entries are invalidated like any other cache entry. If a later SET or SUM breaks the cycle, invalidate clears the stale None values and the cells recompute correctly on the next read.
Complexity
Let k = number of expanded references in a formula, D = cells reachable through reverse from the written cell.
| Operation | Time |
|---|---|
SET | O(old formula size + D) |
SUM | O(k + D) to expand, link, and invalidate; plus O(uncached subgraph) for the immediate evaluation |
GET | O(1) if cached; O(uncached cells + edges below it) otherwise, each cell evaluated once |
Space is O(cells + total expanded references) across all four maps. A single range expands to at most 26 × 1000 = 26 000 cells.
Edge cases
- Uninitialized cell: evaluates to
0; referenced by formulas it contributes0. - Empty refs list:
SUM('A1', [])stores an empty formula;A1evaluates to0. - Self-reference:
SUM('A1', ['A1'])creates an immediate cycle;A1returnsNone. - Reversed range bounds:
'B2:A1'is normalized by sorting column and row bounds independently. - Breaking a cycle: once the cycle is resolved by a
SETorSUM,invalidateclears theNoneentries and normal evaluation resumes. - Deep chains: the implementation is recursive. Very long dependency chains can hit Python's default recursion limit. In a production setting you would either raise the limit or convert
evaluateto an explicit stack.
Full solution
from typing import List, Optional
def spreadsheet_operations(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
values = {}
formulas = {}
reverse = {}
cache = {}
def parse_cell(cell: str):
return cell[0], int(cell[1:])
def expand_ref(ref: str) -> List[str]:
if ':' not in ref:
return [ref]
left, right = ref.split(':', 1)
c1, r1 = parse_cell(left)
c2, r2 = parse_cell(right)
lo_c, hi_c = sorted((ord(c1) - ord('A'), ord(c2) - ord('A')))
lo_r, hi_r = sorted((r1, r2))
result = []
for col in range(lo_c, hi_c + 1):
for row in range(lo_r, hi_r + 1):
result.append(chr(ord('A') + col) + str(row))
return result
def invalidate(cell: str) -> None:
stack = [cell]
seen = set()
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
cache.pop(current, None)
stack.extend(reverse.get(current, ()))
def remove_formula(cell: str) -> None:
old_refs = formulas.pop(cell, None)
if old_refs is not None:
for dep in old_refs:
users = reverse.get(dep)
if users is not None:
users.discard(cell)
if not users:
reverse.pop(dep, None)
def evaluate(cell: str, visiting: set) -> Optional[int]:
if cell in cache:
return cache[cell]
if cell in visiting:
return None
if cell in values:
v = values[cell]
cache[cell] = v
return v
refs = formulas.get(cell)
if refs is None:
cache[cell] = 0
return 0
visiting.add(cell)
total = 0
result: Optional[int] = 0
for dep in refs:
dep_val = evaluate(dep, visiting)
if dep_val is None:
result = None
break
total += dep_val
visiting.remove(cell)
if result is not None:
result = total
cache[cell] = result
return result
output = []
for op, args in zip(operations, arguments):
if op == 'SET':
cell, value = args
remove_formula(cell)
values[cell] = value
invalidate(cell)
output.append(value)
elif op == 'SUM':
cell, refs = args
remove_formula(cell)
values.pop(cell, None)
expanded = []
for ref in refs:
expanded.extend(expand_ref(ref))
formulas[cell] = expanded
for dep in expanded:
reverse.setdefault(dep, set()).add(cell)
invalidate(cell)
output.append(evaluate(cell, set()))
elif op == 'GET':
output.append(evaluate(args[0], set()))
else:
raise ValueError(f'Unknown operation: {op}')
return output