Cycle-Safe Spreadsheet Formula Evaluator
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory grid calculator covering 26 lettered columns (A–Z) and 26 numbered rows (1–26). Every slot starts empty and, once configured, holds either a fixed integer constant or a link to one target slot shifted by an integer delta.
Write run_spreadsheet(commands: List[List]) -> List[str], processing a sequence of operations in order and returning a list containing one status or result string per operation:
["SET_VALUE", cell, value]: Assigns the constant integervaluetocell(discarding any prior constant or link stored there) and appends"OK".["SET_FORMULA", cell, referenced_cell, offset]: Attempts to definecelldynamically as the value ofreferenced_cellplusoffset.- If adding this directed link would form a loop of dependencies (including a slot pointing to itself, or a loop passing through empty slots), reject the command: leave
cellin whatever state it had prior to the call and append"CIRCULAR". - Otherwise, save the new formula on
cell(replacing any previous constant or formula) and append"OK".
- If adding this directed link would form a loop of dependencies (including a slot pointing to itself, or a loop passing through empty slots), reject the command: leave
["GET", cell]: Computes the current value ofcellby following its reference trail:- If
cellis empty, or if following links fromcellreaches an empty slot, append"UNSET". - Otherwise, append the decimal string representation of the resulting integer.
- If
Slot coordinates ignore letter case ("d4" and "D4" refer to the exact same slot), and every address in the input is guaranteed to name a valid coordinate within A1–Z26. Because links are evaluated live, modifying any slot is reflected right away on subsequent "GET" queries for slots downstream of it.
Examples
Example 1
Input:
commands = [
["SET_VALUE", "C2", 15],
["SET_FORMULA", "D2", "c2", -4],
["GET", "D2"],
["SET_VALUE", "C2", 30],
["GET", "d2"],
["SET_FORMULA", "C2", "D2", 5],
["GET", "C2"]
]
Output:
["OK", "OK", "11", "OK", "26", "CIRCULAR", "30"]
Walk-through:
1. C2 is set to 15 ("OK"), and D2 is linked to C2 + (-4) ("OK").
2. Querying D2 evaluates 15 - 4 = 11 ("11").
3. Updating C2 to 30 ("OK") immediately changes d2 (same slot as D2) to 30 - 4 = 26 ("26").
4. Setting C2 = D2 + 5 would close the loop C2 -> D2 -> C2, so it is rejected with "CIRCULAR" and C2 retains 30, which the final "GET" returns ("30").
Example 2
Input:
commands = [
["SET_FORMULA", "F5", "E5", 12],
["GET", "F5"],
["SET_FORMULA", "E5", "E5", 1],
["SET_VALUE", "E5", -7],
["GET", "F5"]
]
Output:
["OK", "UNSET", "CIRCULAR", "OK", "5"]
Walk-through:
1. F5 is defined as E5 + 12 while E5 is still empty ("OK"), so reading F5 produces "UNSET".
2. Pointing E5 to itself (E5 + 1) is a 1-slot loop and is rejected ("CIRCULAR"), leaving E5 empty.
3. Assigning -7 to E5 ("OK") completes the chain so F5 now evaluates to -7 + 12 = 5 ("5").
Constraints
1 <= len(commands) <= 100,000- Every
valueandoffsetis an integer satisfying-10^9 <= value, offset <= 10^9. - Every
"GET"result that resolves to a number fits inside a signed 64-bit integer ([-2^63, 2^63 - 1]). - Every coordinate string has a letter in
A–Z(ora–z) followed by a row number in1–26.
Step-by-step walkthrough
Understand the spreadsheet rules
Our spreadsheet has columns
AthroughZand rows1through26, giving26 * 26 = 676cells in total. At any moment, each cell is in one of three states:- Unset: never given a value or formula yet.
- Plain value: holds a single integer
v. - Formula: holds
ref_cell + offset, pointing to one other cell plus an integer offset.
We process up to
100,000commands and append one response string per command:["SET_VALUE", cell, value]storesvalueincelland outputs"OK".["SET_FORMULA", cell, ref_cell, offset]tries to setcell = ref_cell + offset. If that would create a circular reference (a loop of cells depending on each other), we output"CIRCULAR"and leavecellcompletely unchanged. Otherwise we store the formula and output"OK".["GET", cell]outputs the evaluated integer as a string (such as"26"or"-6"), or"UNSET"ifcellor any cell it depends on is unset.
Cell addresses are case-insensitive (
"c2"and"C2"name the same cell), so we convert every cell name to uppercase right when we read a command.Model the sheet as single-reference chains
We can represent all 676 cells cleanly with two dictionaries:
values: maps a cell name to its plain integer, such as{"C2": 15}.formulas: maps a cell name to(ref_cell, offset), such as{"D2": ("C2", -4)}.
A cell belongs to at most one of these two dictionaries; if it appears in neither, it is unset.
Because every formula references only one cell, each cell has at most one outgoing arrow. That means following references from any cell never branches into a tree—it always walks a single path (a chain):
E2 --(+3)--> D2 --(-4)--> C2 (plain value 15) Value of E2 = 3 + (-4) + 15 = 14Notice what happens if we do not store precomputed formula answers and instead walk the chain fresh on every
GET: wheneverC2changes (orD2is re-pointed toF2), the very nextGETonE2reads the new chain automatically. Because there are only 676 cells and no cycles, any walk takes at most 676 steps.Key idea: detect a cycle by walking from the target cell
A brute-force cycle check would copy the entire spreadsheet, insert the candidate formula, and walk from all 676 cells to see whether any walk loops forever. That works, as our test suite verifies, but scanning the whole sheet on every
SET_FORMULAdoes unnecessary work when only a single arrow is changing.Think about what the sheet looks like right before
["SET_FORMULA", cell, ref_cell, offset]:- Because we rejected every earlier circular update, the current
formulasdictionary contains zero cycles. - Replacing
cell's formula adds only one new arrow:cell -> ref_cell. - Any cycle in the updated sheet must use this new arrow, so the cycle must look like:
new arrow cell ---------> ref_cell ---> ... ---> cell \_____________________/ existing formula chainTherefore,
cell = ref_cell + offsetcreates a cycle if and only if starting atref_celland following existing formulas eventually lands oncell!Two subtle details fall into place automatically when we write this walk:
- Self-reference (
A1 = A1 + 1):start_cellalready equalstarget_cellon the first check, soreachesreturnsTrueimmediately. - Replacing an old formula on
cell: becausereachesreturnsTruethe instantcurrent == target_cell, it stops before looking upformulas[target_cell]. Socell's old formula (which is being overwritten) is never followed. - Unset cells still count in cycles: if
B1 = A1 + 1whileA1is unset, settingA1 = B1 + 0checksreaches(formulas, "B1", "A1"), seesB1 -> A1, and rightly rejects it as"CIRCULAR".
def reaches(formulas: Dict[str, Tuple[str, int]], start_cell: str, target_cell: str) -> bool: """Return True if following formula references from start_cell ever lands on target_cell.""" current = start_cell while True: # Check before looking up formulas[current]: this catches self-references # (start_cell == target_cell) right away and never follows target_cell's # old formula, which is about to be replaced. if current == target_cell: return True if current not in formulas: return False ref_cell, _ = formulas[current] current = ref_cell- Because we rejected every earlier circular update, the current
Walk a chain to evaluate `GET`
To evaluate
start_cell, we start withtotal_offset = 0and followformulasone hop at a time, adding eachoffsetalong the way. Becauseformulasis cycle-free, thewhileloop is guaranteed to stop at some terminal cellcurrentthat is not informulas.At that terminal cell, there are only two possibilities:
currentis not invalues: the chain ended at an unset cell, so the whole chain is unset (None).currentis invalues: the answer istotal_offset + values[current].
def evaluate_cell( values: Dict[str, int], formulas: Dict[str, Tuple[str, int]], start_cell: str, ) -> Optional[int]: """Return the integer value of start_cell, or None if its chain ends at an unset cell.""" total_offset = 0 current = start_cell # Because rejected updates prevent cycles, this chain visits each cell at most once. while current in formulas: ref_cell, offset = formulas[current] total_offset += offset current = ref_cell # The chain stopped at a cell with no formula; it must hold a plain value to be defined. if current not in values: return None return total_offset + values[current]Process each command atomically
Now we wire the three commands together in
run_spreadsheet, keeping the invariant that a cell never lives invaluesandformulasat the same time:SET_VALUE: writevalues[cell] = plain_valueand callformulas.pop(cell, None)to clear any old formula. Removing an arrow can never create a cycle, so this always succeeds with"OK".SET_FORMULA: runreaches(formulas, ref_cell, cell)before touching either dictionary. If it returnsTrue, we append"CIRCULAR"and do nothing else—preserving whatever value, formula, or unset statecellhad before. Otherwise we storeformulas[cell] = (ref_cell, offset)and callvalues.pop(cell, None).GET: callevaluate_celland formatNoneas"UNSET"or an integer asstr(result).
def run_spreadsheet(commands: List[List]) -> List[str]: # values: maps uppercase cell name -> plain integer, e.g. {"C2": 15} values: Dict[str, int] = {} # formulas: maps uppercase cell name -> (referenced_cell, offset), e.g. {"D2": ("C2", -4)} # Invariant: a cell is in at most one of `values` or `formulas` (neither means unset), # and `formulas` never contains a dependency cycle. formulas: Dict[str, Tuple[str, int]] = {} output: List[str] = [] for command in commands: op = command[0] cell = command[1].upper() if op == "SET_VALUE": plain_value = int(command[2]) values[cell] = plain_value # Overwriting with a plain integer removes any previous formula on this cell. formulas.pop(cell, None) output.append("OK") elif op == "SET_FORMULA": ref_cell = command[2].upper() offset = int(command[3]) # Adding edge (cell -> ref_cell) creates a cycle if and only if ref_cell # already reaches cell through existing formulas. Checking before writing # keeps rejected updates atomic (old state stays untouched). if reaches(formulas, ref_cell, cell): output.append("CIRCULAR") else: formulas[cell] = (ref_cell, offset) values.pop(cell, None) output.append("OK") elif op == "GET": result = evaluate_cell(values, formulas, cell) if result is None: output.append("UNSET") else: output.append(str(result)) return outputTrace Example 1 step by step
Let's trace the seven commands from Example 1:
Command Check / Walk Sheet state after Output -------------------------------------------------------------------------------------------------------- 1. SET_VALUE C2 15 write plain value values={C2: 15}, formulas={} "OK" 2. SET_FORMULA D2 = c2 + (-4) reaches(C2, D2)? values={C2: 15}, "OK" C2 not in formulas -> False formulas={D2: (C2, -4)} 3. GET D2 D2 --(-4)--> C2 (15) unchanged "11" -4 + 15 = 11 4. SET_VALUE C2 30 overwrite plain value values={C2: 30}, "OK" formulas={D2: (C2, -4)} 5. GET d2 D2 --(-4)--> C2 (30) unchanged "26" -4 + 30 = 26 6. SET_FORMULA C2 = D2 + 5 reaches(D2, C2)? unchanged! C2 keeps plain value 30 "CIRCULAR" D2 -> C2 == target -> True 7. GET C2 C2 in values -> 30 unchanged "30"The returned list is
["OK", "OK", "11", "OK", "26", "CIRCULAR", "30"], matching Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def reaches(formulas: Dict[str, Tuple[str, int]], start_cell: str, target_cell: str) -> bool: """Return True if following formula references from start_cell ever lands on target_cell.""" current = start_cell while True: # Check before looking up formulas[current]: this catches self-references # (start_cell == target_cell) right away and never follows target_cell's # old formula, which is about to be replaced. if current == target_cell: return True if current not in formulas: return False ref_cell, _ = formulas[current] current = ref_cell def evaluate_cell( values: Dict[str, int], formulas: Dict[str, Tuple[str, int]], start_cell: str, ) -> Optional[int]: """Return the integer value of start_cell, or None if its chain ends at an unset cell.""" total_offset = 0 current = start_cell # Because rejected updates prevent cycles, this chain visits each cell at most once. while current in formulas: ref_cell, offset = formulas[current] total_offset += offset current = ref_cell # The chain stopped at a cell with no formula; it must hold a plain value to be defined. if current not in values: return None return total_offset + values[current] def run_spreadsheet(commands: List[List]) -> List[str]: # values: maps uppercase cell name -> plain integer, e.g. {"C2": 15} values: Dict[str, int] = {} # formulas: maps uppercase cell name -> (referenced_cell, offset), e.g. {"D2": ("C2", -4)} # Invariant: a cell is in at most one of `values` or `formulas` (neither means unset), # and `formulas` never contains a dependency cycle. formulas: Dict[str, Tuple[str, int]] = {} output: List[str] = [] for command in commands: op = command[0] cell = command[1].upper() if op == "SET_VALUE": plain_value = int(command[2]) values[cell] = plain_value # Overwriting with a plain integer removes any previous formula on this cell. formulas.pop(cell, None) output.append("OK") elif op == "SET_FORMULA": ref_cell = command[2].upper() offset = int(command[3]) # Adding edge (cell -> ref_cell) creates a cycle if and only if ref_cell # already reaches cell through existing formulas. Checking before writing # keeps rejected updates atomic (old state stays untouched). if reaches(formulas, ref_cell, cell): output.append("CIRCULAR") else: formulas[cell] = (ref_cell, offset) values.pop(cell, None) output.append("OK") elif op == "GET": result = evaluate_cell(values, formulas, cell) if result is None: output.append("UNSET") else: output.append(str(result)) return output✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a wall of 676 mail cubbies labeled A1 through Z26. Each cubby is either empty (unset), holds a card with a plain number, or holds a forwarding note that says "take the number from cubby X and add an offset." Because each forwarding note names only one other cubby, following notes from any cubby always walks a single straight trail—never a branching tree. And if you want to put a new forwarding note cell -> ref_cell into cell, it can only create an endless loop (a circular reference, meaning a chain of dependencies that loops back onto itself) if following existing notes from ref_cell already leads right back to cell.
Two naive approaches run into trouble here. If you compute and save a formula's numeric answer at the moment SET_FORMULA is called, then changing C2 later leaves D2 and E2 holding stale, outdated numbers unless you also maintain reverse links to update every dependent cell. On the other hand, if you check for cycles by copying the entire spreadsheet and hunting for loops from every cell on each SET_FORMULA, you do up to 676 walks of 676 steps when a single walk starting at ref_cell is enough.
Here is how our two-dictionary design (values for plain numbers, formulas for (ref_cell, offset) pairs) handles Example 1:
SET_VALUE C2 15-> storesvalues["C2"] = 15and outputs"OK".SET_FORMULA D2 c2 -4-> normalizes"c2"to"C2"and walks fromC2looking forD2;C2has no formula, so there is no cycle. Storesformulas["D2"] = ("C2", -4)and outputs"OK".GET D2-> walksD2 --(-4)--> C2 (15)and outputs"11".SET_VALUE C2 30-> updatesvalues["C2"] = 30("OK"), so the nextGET d2immediately walksD2 --(-4)--> C2 (30)and outputs"26".SET_FORMULA C2 D2 5-> walks fromD2looking forC2;D2points toC2, so a cycle would form! Rejects with"CIRCULAR"without touchingvalues["C2"], andGET C2still outputs"30".
Complexity
Let C = 676 be the fixed number of cells (A1 through Z26) and m = len(commands) be the number of commands.
- Time: O(m * C), which is O(m) because C = 676 is constant.
SET_VALUEdoes O(1) dictionary updates. BothSET_FORMULA(walking fromref_cellto check for a cycle) andGET(walking the formula chain to sum offsets) visit each of theCcells at most once because the sheet never contains a cycle, taking at most 676 loop steps per command. - Space: O(C) extra space (excluding the output list of length m). Each of the 676 cells appears in at most one of
valuesorformulas, so the dictionaries hold at most 676 entries combined.
Edge cases
GETon a never-set cell: not informulasand not invalues, soevaluate_cellreturnsNoneand we emit"UNSET".- Unset cell deep inside a chain: if
C1 -> B1 -> A1andA1is unset,GET C1walks toA1, sees it missing fromvalues, and emits"UNSET"; as soon asSET_VALUE A1 2runs,GET C1immediately evaluates the whole chain. - Self-reference (
A1 = A1 + 1):reachescheckscurrent == target_cellbefore anything else, immediately returningTrueand emitting"CIRCULAR"while preservingA1's previous state. - Cycle through an unset cell: cycle detection inspects
formulasonly, notvalues, soB1 = A1 + 1followed byA1 = B1 + 0is rejected as"CIRCULAR"even whenA1has no value. - Atomic rejection (
"CIRCULAR"): because we checkreachesbefore mutatingformulasorvalues, a rejected formula leaves the target cell's previous plain value, previous formula, or unset status intact. - Overwriting a formula with a value:
SET_VALUE B1 5removesB1fromformulas, breaking the old dependency link soA1 = B1 + 1is later allowed. - Case-insensitive addresses:
"a1"and"A1"map to"A1"in all three commands, including cycle checks. - 64-bit integer range: a 676-cell chain with offsets of
10^9reaches roughly6.76 * 10^11, which exceeds 32-bit signed integers; Python's arbitrary-precision integers handle this automatically, while C++/Java/Rust solutions should useint64_t/long/i64.
Common mistakes
- Caching evaluated numbers on write without reverse updates: saving
D2 = 11atSET_FORMULAtime makesD2return a stale value afterSET_VALUE C2 30. - Following the updated cell's old formula during cycle detection: starting the walk at
cellinstead ofref_cell(or failing to stop as soon ascurrent == cell) accidentally traverses the old formula edge that is about to be replaced. - Mutating first and trying to roll back on
"CIRCULAR": overwritingformulas[cell]before checking makes it easy to losecell's old plain value invalues; checking first makes rejection atomic with zero rollback code. - Forgetting to remove the cell from the other dictionary: leaving
"C2"in bothvaluesandformulascausesevaluate_cellto follow a stale formula afterSET_VALUEor read a stale value. - Using recursion without considering chain depth: a chain of 676 cells comes close to Python's default recursion limit of 1,000 (and exceeds it on larger grids); a simple
whileloop uses O(1) stack space. - Uppercasing
cellbut forgettingref_cell:"d2"pointing to"c2"will miss"C2"invaluesunless both cell arguments are uppercased.
Alternative approaches
- Push updates on write using reverse dependency lists: store each cell's current evaluated result alongside
dependents[x](the set of cells whose formula directly referencesx).GETbecomes O(1), whileSET_VALUEandSET_FORMULAwalk downstream dependents in O(C) time using breadth-first search (BFS)—a graph traversal that visits nodes level by level using a queue. This trades slower writes for O(1) reads whenGETqueries heavily outnumber writes. - Whole-sheet cycle check on a copy: copy
formulas, insert the candidate formula, and verify from every cell that walks take at mostCsteps. Simple to reason about (and great as a test oracle), thoughCtimes slower onSET_FORMULA.
Follow-up questions
- How would your design change if a formula could sum two or more referenced cells, such as M1 = K1 + L2 + 5? Dependencies then form a directed acyclic graph (DAG)—a network of one-way arrows with no loops, where paths can branch and reconverge—rather than single chains. Cycle detection runs a BFS or depth-first search starting from all cells referenced by the new formula to check whether any path reaches
cell. DuringGET, two branches can reconverge on the same shared cell (a diamond pattern that would otherwise double-count work exponentially), so you should use memoization—caching each cell's result in a temporary dictionary during a singleGETcall so every cell in the DAG is evaluated at most once. - If reads vastly outnumber writes (for example, 99.9% GET commands), how can you make GET run in O(1) time? Maintain a cached evaluated value (
intorNonefor unset) for every cell plus a reverse adjacency mapdependents[x]listing cells that directly referencex. NowGETis a single O(1) dictionary lookup, and wheneverSET_VALUEor an acceptedSET_FORMULAchanges a cell, you recompute that cell and propagate the update forward throughdependentsin O(C) time. - How would you scale this design to millions of cells where dependency chains can reach 100,000 hops? Walking a chain in O(chain length) per
GETorSET_FORMULAwould time out. Because each cell still has at most one outgoing reference, the spreadsheet forms a collection of directed trees (a forest) where a cell's value is its root's value plus the sum of offsets along the path to the root; a link-cut tree—an advanced dynamic-tree data structure that maintains path aggregates under edge insertions and deletions—can check reachability, re-point formulas, and query path sums in O(log N) amortized time per command.
Follow-up questions
- How would your design change if a formula could sum two or more referenced cells, such as M1 = K1 + L2 + 5?
- If reads vastly outnumber writes (for example, 99.9% GET commands), how can you make GET run in O(1) time?
- How would you scale this design to millions of cells where dependency chains can reach 100,000 hops?
Similar questions
- Fixed-Width Line Packing and Subarray Product Sum
- 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