Linked Cell Grid with Cycle-Safe Formula Updates
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a 26x26 grid whose cells hold integers or one-reference offset formulas, answering lookups lazily and rejecting any formula assignment that would close a dependency loop.
Problem
You are building a tiny spreadsheet. Its columns are A through Z and its rows are 1 through 26. Each cell can be in one of three states:
- empty (never assigned),
- holding a literal integer, or
- holding a formula of the form
target = source + offset, wheresourceis another cell (or the cell itself) andoffsetis an integer.
A formula always reads the current content of its source cell, so any later change to a cell is immediately visible to every formula that depends on it, directly or through a chain.
Write a function that processes a list of commands in order and returns one output string per command.
Commands
Each command is a list whose first element is the operation name.
-
["SET_VALUE", cell, value]Store the integervalueincell, replacing whatever it held before (a literal or a formula). Output"OK". -
["SET_FORMULA", cell, source_cell, offset]Makecellhold the formulasource_cell + offset, replacing its previous content.- If this assignment would produce a circular dependency (including
cellreferring to itself, directly or through any chain of formulas), the command is rejected: the spreadsheet stays exactly as it was, including the previous content ofcell, and the output is"CIRCULAR". - Otherwise the formula is stored and the output is
"OK".
- If this assignment would produce a circular dependency (including
-
["GET", cell]Output the current integer value ofcellas a decimal string (for example"30"or"-7"). Ifcellis empty, or following its chain of formulas reaches an empty cell, output"UNSET".
Notes
- Cell names are case-insensitive:
"b1"and"B1"denote the same cell. Every address in the input is well formed. - A cell referenced by a formula may be empty at the time the formula is stored. That is allowed; the formula simply evaluates to
"UNSET"until the source gets a value. - Return the list of output strings in the same order as the commands.
Constraints
1 <= len(commands) <= 100000- Literal values and offsets are integers in
[-10^9, 10^9]. - Every evaluated result fits in a signed 64-bit integer.
- All cell addresses are valid and lie within
A1toZ26(case-insensitive).
Examples
Example 1
Input: simulate_cell_grid([['SET_VALUE', 'A1', 20], ['SET_FORMULA', 'B1', 'A1', 10], ['GET', 'B1'], ['SET_FORMULA', 'A1', 'B1', 0], ['GET', 'A1']])
Output: ['OK', 'OK', '30', 'CIRCULAR', '20']
Hints
Hint 1
Each formula names exactly one source cell, so every cell has at most one outgoing dependency. The dependencies therefore form simple chains rather than a general graph.
Hint 2
To decide whether `cell = source + k` creates a loop, walk the chain that starts at `source`. If you ever arrive at `cell`, the update is circular. Starting the walk at `source == cell` handles self-reference automatically.
Hint 3
You do not need to push updates to dependents. Store literals and formulas as they are and compute a value on demand by following the chain, adding offsets until you hit a literal (or an empty cell, which gives UNSET). Only commit a new formula after the cycle check passes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every formula refers to exactly one source cell. Draw an edge cell -> source for each formula: each cell then has at most one outgoing edge, so the dependency structure is a set of chains.
Store two dictionaries:
literals[cell]for cells holding an integer,formulas[cell] = (source, offset)for cells holding a formula.
A cell is in at most one of them. All addresses are upper-cased so matching is case-insensitive.
SET_VALUE writes the literal and removes any formula for that cell. Removing an outgoing edge can never create a loop, so the answer is always "OK".
SET_FORMULA (cell = source + offset): the new edge cell -> source closes a loop exactly when cell is already reachable from source. Because each node has one outgoing edge, this is just a walk along the chain starting at source. If the walk meets cell, output "CIRCULAR" and change nothing. If source == cell, the walk meets it immediately, so self-reference is caught. Otherwise delete any literal in cell, store the formula, and output "OK". The old formula of cell does not interfere with the check: if the walk from source reaches cell, it has found the target before using cell's old edge.
GET: walk the chain from the cell, accumulating offsets. If a literal is reached, the answer is the accumulated offsets plus that literal. If an empty cell is reached, the answer is "UNSET".
Values are computed lazily, so there is nothing to propagate or invalidate when a cell changes; every GET reads the current state.
Why it is correct
The formula graph is always acyclic. It starts empty; SET_VALUE only removes edges; and SET_FORMULA is accepted only when the new edge cannot lie on a cycle. Any new cycle would have to use the new edge, which requires a path from source back to cell, and that is exactly what is tested. With no cycles, every chain terminates at a literal or an empty cell, so evaluation is well defined and always reflects the latest updates. A rejected command leaves both dictionaries untouched, preserving the old content.
Complexity
There are at most 26 * 26 = 676 cells, so every chain has length at most 676.
SET_VALUE: O(1).SET_FORMULAandGET: O(676) each.- Total time: O(n * 676) in the worst case, where n is the number of commands.
- Space: O(676) for the dictionaries and the temporary visited sets.
Reference solution
from typing import List
def simulate_cell_grid(commands: List[List]) -> List[str]:
literals = {} # cell -> int
formulas = {} # cell -> (source_cell, offset)
out = []
def reaches(start, target):
# Follow the single-successor chain from start; True if target is met.
current = start
seen = set()
while True:
if current == target:
return True
if current in seen:
return False
seen.add(current)
if current in formulas:
current = formulas[current][0]
else:
return False
def evaluate(cell):
total = 0
current = cell
seen = set()
while True:
if current in literals:
return total + literals[current]
if current not in formulas or current in seen:
return None
seen.add(current)
src, off = formulas[current]
total += off
current = src
for cmd in commands:
op = cmd[0]
cell = cmd[1].upper()
if op == "SET_VALUE":
literals[cell] = cmd[2]
formulas.pop(cell, None)
out.append("OK")
elif op == "SET_FORMULA":
src = cmd[2].upper()
off = cmd[3]
if reaches(src, cell):
out.append("CIRCULAR")
else:
literals.pop(cell, None)
formulas[cell] = (src, off)
out.append("OK")
else:
val = evaluate(cell)
out.append("UNSET" if val is None else str(val))
return out