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 integer value to cell (discarding any prior constant or link stored there) and appends "OK".
  • ["SET_FORMULA", cell, referenced_cell, offset]: Attempts to define cell dynamically as the value of referenced_cell plus offset.
    • 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 cell in 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".
  • ["GET", cell]: Computes the current value of cell by following its reference trail:
    • If cell is empty, or if following links from cell reaches an empty slot, append "UNSET".
    • Otherwise, append the decimal string representation of the resulting integer.

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 value and offset is 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 (or a–z) followed by a row number in 1–26.

Step-by-step walkthrough

  1. Understand the spreadsheet rules

    Our spreadsheet has columns A through Z and rows 1 through 26, giving 26 * 26 = 676 cells in total. At any moment, each cell is in one of three states:

    1. Unset: never given a value or formula yet.
    2. Plain value: holds a single integer v.
    3. Formula: holds ref_cell + offset, pointing to one other cell plus an integer offset.

    We process up to 100,000 commands and append one response string per command:

    • ["SET_VALUE", cell, value] stores value in cell and outputs "OK".
    • ["SET_FORMULA", cell, ref_cell, offset] tries to set cell = ref_cell + offset. If that would create a circular reference (a loop of cells depending on each other), we output "CIRCULAR" and leave cell completely 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" if cell or 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.

  2. 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 = 14
    

    Notice what happens if we do not store precomputed formula answers and instead walk the chain fresh on every GET: whenever C2 changes (or D2 is re-pointed to F2), the very next GET on E2 reads the new chain automatically. Because there are only 676 cells and no cycles, any walk takes at most 676 steps.

  3. 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_FORMULA does 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 formulas dictionary 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 chain
    

    Therefore, cell = ref_cell + offset creates a cycle if and only if starting at ref_cell and following existing formulas eventually lands on cell!

    Two subtle details fall into place automatically when we write this walk:

    1. Self-reference (A1 = A1 + 1): start_cell already equals target_cell on the first check, so reaches returns True immediately.
    2. Replacing an old formula on cell: because reaches returns True the instant current == target_cell, it stops before looking up formulas[target_cell]. So cell's old formula (which is being overwritten) is never followed.
    3. Unset cells still count in cycles: if B1 = A1 + 1 while A1 is unset, setting A1 = B1 + 0 checks reaches(formulas, "B1", "A1"), sees B1 -> 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
    
  4. Walk a chain to evaluate `GET`

    To evaluate start_cell, we start with total_offset = 0 and follow formulas one hop at a time, adding each offset along the way. Because formulas is cycle-free, the while loop is guaranteed to stop at some terminal cell current that is not in formulas.

    At that terminal cell, there are only two possibilities:

    • current is not in values: the chain ended at an unset cell, so the whole chain is unset (None).
    • current is in values: the answer is total_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]
    
  5. Process each command atomically

    Now we wire the three commands together in run_spreadsheet, keeping the invariant that a cell never lives in values and formulas at the same time:

    • SET_VALUE: write values[cell] = plain_value and call formulas.pop(cell, None) to clear any old formula. Removing an arrow can never create a cycle, so this always succeeds with "OK".
    • SET_FORMULA: run reaches(formulas, ref_cell, cell) before touching either dictionary. If it returns True, we append "CIRCULAR" and do nothing else—preserving whatever value, formula, or unset state cell had before. Otherwise we store formulas[cell] = (ref_cell, offset) and call values.pop(cell, None).
    • GET: call evaluate_cell and format None as "UNSET" or an integer as str(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 output
    
  6. Trace 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.

  7. 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:

  1. SET_VALUE C2 15 -> stores values["C2"] = 15 and outputs "OK".
  2. SET_FORMULA D2 c2 -4 -> normalizes "c2" to "C2" and walks from C2 looking for D2; C2 has no formula, so there is no cycle. Stores formulas["D2"] = ("C2", -4) and outputs "OK".
  3. GET D2 -> walks D2 --(-4)--> C2 (15) and outputs "11".
  4. SET_VALUE C2 30 -> updates values["C2"] = 30 ("OK"), so the next GET d2 immediately walks D2 --(-4)--> C2 (30) and outputs "26".
  5. SET_FORMULA C2 D2 5 -> walks from D2 looking for C2; D2 points to C2, so a cycle would form! Rejects with "CIRCULAR" without touching values["C2"], and GET C2 still 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_VALUE does O(1) dictionary updates. Both SET_FORMULA (walking from ref_cell to check for a cycle) and GET (walking the formula chain to sum offsets) visit each of the C cells 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 values or formulas, so the dictionaries hold at most 676 entries combined.

Edge cases

  • GET on a never-set cell: not in formulas and not in values, so evaluate_cell returns None and we emit "UNSET".
  • Unset cell deep inside a chain: if C1 -> B1 -> A1 and A1 is unset, GET C1 walks to A1, sees it missing from values, and emits "UNSET"; as soon as SET_VALUE A1 2 runs, GET C1 immediately evaluates the whole chain.
  • Self-reference (A1 = A1 + 1): reaches checks current == target_cell before anything else, immediately returning True and emitting "CIRCULAR" while preserving A1's previous state.
  • Cycle through an unset cell: cycle detection inspects formulas only, not values, so B1 = A1 + 1 followed by A1 = B1 + 0 is rejected as "CIRCULAR" even when A1 has no value.
  • Atomic rejection ("CIRCULAR"): because we check reaches before mutating formulas or values, 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 5 removes B1 from formulas, breaking the old dependency link so A1 = B1 + 1 is 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^9 reaches roughly 6.76 * 10^11, which exceeds 32-bit signed integers; Python's arbitrary-precision integers handle this automatically, while C++/Java/Rust solutions should use int64_t / long / i64.

Common mistakes

  • Caching evaluated numbers on write without reverse updates: saving D2 = 11 at SET_FORMULA time makes D2 return a stale value after SET_VALUE C2 30.
  • Following the updated cell's old formula during cycle detection: starting the walk at cell instead of ref_cell (or failing to stop as soon as current == cell) accidentally traverses the old formula edge that is about to be replaced.
  • Mutating first and trying to roll back on "CIRCULAR": overwriting formulas[cell] before checking makes it easy to lose cell's old plain value in values; checking first makes rejection atomic with zero rollback code.
  • Forgetting to remove the cell from the other dictionary: leaving "C2" in both values and formulas causes evaluate_cell to follow a stale formula after SET_VALUE or 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 while loop uses O(1) stack space.
  • Uppercasing cell but forgetting ref_cell: "d2" pointing to "c2" will miss "C2" in values unless 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 references x). GET becomes O(1), while SET_VALUE and SET_FORMULA walk 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 when GET queries 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 most C steps. Simple to reason about (and great as a test oracle), though C times slower on SET_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. During GET, 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 single GET call 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 (int or None for unset) for every cell plus a reverse adjacency map dependents[x] listing cells that directly reference x. Now GET is a single O(1) dictionary lookup, and whenever SET_VALUE or an accepted SET_FORMULA changes a cell, you recompute that cell and propagate the update forward through dependents in 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 GET or SET_FORMULA would 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

Similar questions

More Pika interview questions

All 2 Pika questions →