Formula Spreadsheet With Cycle Rejection

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Build an in-memory spreadsheet engine capable of storing integer literals and additive cell formulas while rejecting circular dependencies.

Cells are addressed by coordinate labels such as "R1", "K2", or "X10". Each operation in a replay script is dispatched through:

def apply_spreadsheet_operations(
    operations: List[str], arguments: List[List[object]]
) -> List[object]:

For each index i, operations[i] and arguments[i] specify one of two commands on a single shared sheet:

  1. "setCell" with [cell_name, value_or_formula] -> bool:
    • value_or_formula is either an int (positive, zero, or negative) or a formula str made of +-separated terms (with optional surrounding whitespace and an optional leading "="). Every term is either a signed/unsigned integer literal or a cell label, and a cell label may appear multiple times in the same formula (for instance, "R1 + R1" contributes twice R1's value).
    • Cycle rejection: If assigning value_or_formula to cell_name would introduce a self-reference or a closed dependency loop among formulas, reject the write: leave the entire sheet unchanged (keeping cell_name's prior definition, if any) and return False.
    • Otherwise, store the new definition on cell_name (replacing any previous literal or formula on cell_name) and return True.
  2. "getCell" with [cell_name] -> int:
    • Compute and return the current integer value of cell_name.
    • Any cell that has never been successfully assigned evaluates to 0, both when queried directly and when referenced inside another formula.
    • Subsequent updates to upstream cells must automatically be reflected on future "getCell" queries.

Return a list containing the return value of every operation in order.

Examples

Example 1

  • Input:
    • operations = ["setCell", "setCell", "getCell", "setCell", "setCell", "getCell"]
    • arguments = [["R1", 6], ["T1", "R1 + S1 + 3"], ["T1"], ["S1", 9], ["R1", -2], ["T1"]]
  • Output: [True, True, 9, True, True, 10]
  • Explanation: R1 becomes 6, and T1 is set to "R1 + S1 + 3". On the first getCell("T1"), unassigned S1 defaults to 0, giving 6 + 0 + 3 = 9. After setting S1 = 9 and updating R1 = -2, reading T1 again reflects both updates: -2 + 9 + 3 = 10.

Example 2

  • Input:
    • operations = ["setCell", "setCell", "setCell", "getCell", "getCell", "setCell", "getCell"]
    • arguments = [["K2", 8], ["K1", "K2 + K3"], ["K2", "K1 + 4"], ["K2"], ["K1"], ["K3", 5], ["K1"]]
  • Output: [True, True, False, 8, 8, True, 13]
  • Explanation: K2 is 8 and K1 reads K2 + K3. Attempting setCell("K2", "K1 + 4") would close the loop K2 -> K1 -> K2, so it returns False and leaves K2 at 8. Reading K2 and K1 both yield 8; once K3 is set to 5, getCell("K1") returns 8 + 5 = 13.

Constraints

  • 1 <= len(operations) == len(arguments) <= 2,000
  • Every operations[i] is either "setCell" or "getCell".
  • Cell labels are non-empty alphanumeric strings beginning with a letter (such as "R1" or "A1500").
  • Formula graphs may form chains over 1,500 cells deep or diamond/shared subgraphs (such as 60-level doubling ladders), so evaluation must avoid exponential recomputation and call-stack overflow.

Step-by-step walkthrough

  1. Understand the operations and rules

    The judge replays a sequence of calls on one in-memory spreadsheet. For each index i, operations[i] names the method and arguments[i] holds its arguments:

    • setCell(cell, value) assigns either an integer (such as 6 or -2) or a +-joined formula string (such as "R1 + S1 + 3"). It returns True if the assignment succeeds, or False if it would introduce a circular dependency. When a write returns False, the entire sheet stays untouched.
    • getCell(cell) returns the current evaluated integer value of cell. Any cell that has never been assigned—either queried directly or referenced inside another formula—evaluates to 0.

    Whenever an upstream cell changes later, subsequent getCell calls on cells that depend on it must reflect the updated value.

  2. Choose lazy vs. eager evaluation

    A spreadsheet engine has to decide when to turn formulas into numbers:

    • Eager evaluation computes and caches every cell's integer value on each setCell, walking forward through all dependent cells in topological order to refresh them. Reads become a single dictionary lookup, at the cost of extra bookkeeping on every write.
    • Lazy evaluation stores only the parsed formula on setCell and computes the integer value on demand during getCell. Because no computed numbers persist across operations, a read can never return a stale value after an upstream update.

    Since no read-heavy ratio is imposed here, lazy evaluation gives us the cleanest design: a single dictionary self.formulas serves simultaneously as formula storage and the dependency graph.

    Spreadsheet state in Example 1 after R1 = -2, S1 = 9, T1 = "R1 + S1 + 3":
    
      self.formulas = {
          "R1": (-2, []),
          "S1": (9, []),
          "T1": (3, ["R1", "S1"]),
      }
    
  3. Parse integers and formulas into one uniform shape

    If plain integers and formula strings share the exact same internal representation, the evaluator never needs separate branches for them. Every cell definition reduces to a constant integer sum plus a list of referenced cell labels:

    Input value         Parsed (constant_sum, referenced_cells)
    -----------------------------------------------------------
    6                -> (6, [])
    "R1 + S1 + 3"    -> (3, ["R1", "S1"])
    "R1 + R1"        -> (0, ["R1", "R1"])
    

    Notice that referenced_cells is a List[str], not a Set[str]: in "R1 + R1", cell R1 contributes its value twice, so duplicate references must be kept. Splitting on "+", stripping spaces, and checking whether each piece is an optional sign followed by digits handles constants (including negative integers), cell names, and optional leading "=" signs.

    Formula = Tuple[int, List[str]]
    
    
    def is_integer_literal(term: str) -> bool:
        """Return True if `term` is an optional +/- sign followed by digits."""
        if term.startswith("-") or term.startswith("+"):
            term = term[1:]
        return len(term) > 0 and term.isdigit()
    
    
    def parse_formula(value: object) -> Formula:
        """Convert an integer or formula string into (constant_sum, referenced_cells)."""
        if isinstance(value, int):
            return value, []
    
        text = str(value).strip()
        if text.startswith("="):
            text = text[1:]
    
        constant_sum = 0
        referenced_cells: List[str] = []
        for raw_part in text.split("+"):
            term = raw_part.strip()
            if not term:
                continue
            if is_integer_literal(term):
                constant_sum += int(term)
            else:
                # Keep a list (not a set) so "A1 + A1" counts A1's value twice.
                referenced_cells.append(term)
        return constant_sum, referenced_cells
    
  4. Detect circular dependencies before modifying the sheet

    Think of formulas as directed arrows from a cell to the inputs it reads. Writing K2 = "K1 + 4" adds a new arrow K2 -> K1. When does that create a cycle? Exactly when K1 (or one of the other new references) already has a path of arrows leading to K2—or is K2 itself (K2 = "K2 + 1"):

    Existing formulas: K2 = 8, K1 = "K2 + K3"
      K1 ---> K2
      K1 ---> K3
    
    Proposed write: K2 = "K1 + 4"
      Start search at ["K1"]:
        "K1" reads ["K2", "K3"] -> reaches target "K2"!
      Adding K2 -> K1 would close the loop K2 -> K1 -> K2 -> REJECT (return False, K2 stays 8)
    

    Two details make this check bug-free:

    1. Check before mutating: Run the reachability search before writing to self.formulas[cell]. If a cycle would form, simply return False—nothing was mutated, so K2's prior value 8 survives untouched.
    2. Old formula cannot cause false alarms: What if cell already had an old formula? Our search checks if current == target_cell: return True the instant it pops cell, before ever reading self.formulas[cell]. So cell's old outgoing arrows are never traversed, and overwriting self.formulas[cell] afterward automatically discards them.
    class Spreadsheet:
        def __init__(self) -> None:
            # self.formulas: maps cell_name -> (constant_sum, referenced_cells),
            # e.g. {"R1": (6, []), "T1": (3, ["R1", "S1"])}
            self.formulas: Dict[str, Formula] = {}
    
        def set_cell(self, cell: str, value: object) -> bool:
            """Save the parsed formula, or return False without changing anything if it creates a cycle."""
            constant_sum, referenced_cells = parse_formula(value)
    
            # Phase 1: check for a cycle BEFORE mutating self.formulas so a rejected write
            # leaves the existing spreadsheet untouched with nothing to roll back.
            if self._reaches_target(referenced_cells, cell):
                return False
    
            # Phase 2: store the new formula (overwriting automatically drops any old references).
            self.formulas[cell] = (constant_sum, referenced_cells)
            return True
    
        def _reaches_target(self, start_cells: List[str], target_cell: str) -> bool:
            """Return True if `target_cell` is in `start_cells` or reachable via their formula inputs."""
            # visited: set of cell names already expanded during this graph search
            visited: Set[str] = set()
            stack: List[str] = list(start_cells)
    
            while stack:
                current = stack.pop()
                # Checking `current == target_cell` right away catches self-loops (A1 = A1 + 1)
                # and stops before expanding target_cell's old formula, avoiding false cycles.
                if current == target_cell:
                    return True
                if current in visited:
                    continue
                visited.add(current)
    
                _, next_refs = self.formulas.get(current, (0, []))
                stack.extend(next_refs)
    
            return False
    
  5. Evaluate formulas iteratively with memoization

    To evaluate a cell, we sum its constant_sum and the values of its referenced_cells. Writing that as a plain recursive function hits two traps:

    1. Repeated work on shared cells: If X1 = X0 + X0, X2 = X1 + X1, ..., up to X60, naive recursion evaluates X0 2^60 separate times. Saving each cell's result in a computed_values dictionary during the read (memoization) guarantees every reachable cell is evaluated once.
    2. Call-stack overflow on deep chains: A chain of 1500 cells (A2 = A1 + 1, ..., A1500 = A1499 + 1) exceeds Python's default recursion limit of 1000 frames.

    An explicit eval_stack solves both problems cleanly. Peek at the cell on top of eval_stack: if any of its referenced inputs are not in computed_values yet, keep current on the stack and push those missing inputs on top so they finish first. When current is on top again, all of its inputs are ready in computed_values, so we sum them, save computed_values[current], and pop current:

    Evaluating getCell("T1") when R1 = -2, S1 = 9, T1 = (3, ["R1", "S1"]):
    
      Step 1: eval_stack = ["T1"], computed_values = {}
              "T1" is missing ["R1", "S1"] -> push them above "T1"
      Step 2: eval_stack = ["T1", "R1", "S1"]
              top is "S1" -> no missing inputs -> computed_values["S1"] = 9, pop "S1"
      Step 3: eval_stack = ["T1", "R1"]
              top is "R1" -> no missing inputs -> computed_values["R1"] = -2, pop "R1"
      Step 4: eval_stack = ["T1"]
              top is "T1" -> all inputs ready -> 3 + (-2) + 9 = 10 -> pop "T1"
    

    Unassigned cells are simply absent from self.formulas, so .get(current, (0, [])) evaluates them to 0 automatically.

        def get_cell(self, cell: str) -> int:
            """Evaluate `cell` from the current formulas; unassigned cells default to 0."""
            computed_values: Dict[str, int] = {}
            eval_stack: List[str] = [cell]
    
            while eval_stack:
                current = eval_stack[-1]
                if current in computed_values:
                    eval_stack.pop()
                    continue
    
                constant_sum, referenced_cells = self.formulas.get(current, (0, []))
                missing_inputs: List[str] = []
                for ref in referenced_cells:
                    if ref not in computed_values:
                        missing_inputs.append(ref)
    
                if missing_inputs:
                    eval_stack.extend(missing_inputs)
                    continue
    
                total = constant_sum
                for ref in referenced_cells:
                    total += computed_values[ref]
                computed_values[current] = total
                eval_stack.pop()
    
            return computed_values[cell]
    
  6. Wire up the operation dispatcher

    The judged entry point creates one Spreadsheet instance, dispatches each operation in operations with its matching arguments entry, and collects the return values in order.

    def apply_spreadsheet_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
        sheet = Spreadsheet()
        results: List[object] = []
        for op, args in zip(operations, arguments):
            if op == "setCell":
                cell_name = str(args[0])
                results.append(sheet.set_cell(cell_name, args[1]))
            elif op == "getCell":
                cell_name = str(args[0])
                results.append(sheet.get_cell(cell_name))
            else:
                raise ValueError("unknown operation: " + op)
        return results
    
  7. Trace Example 2 step by step

    Let's trace every call in Example 2 to watch cycle rejection and preserved state work together:

    Call 1: setCell("K2", 8)
      parsed = (8, []), _reaches_target([], "K2") -> False
      formulas = {"K2": (8, [])}                          -> returns True
    
    Call 2: setCell("K1", "K2 + K3")
      parsed = (0, ["K2", "K3"])
      _reaches_target(["K2", "K3"], "K1") -> False
      formulas = {"K2": (8, []), "K1": (0, ["K2", "K3"])} -> returns True
    
    Call 3: setCell("K2", "K1 + 4")
      parsed = (4, ["K1"])
      _reaches_target(["K1"], "K2"):
        pop "K1" -> push its refs ["K2", "K3"]
        pop "K3" -> unassigned -> []
        pop "K2" -> matches target "K2"!                  -> returns False
      formulas["K2"] stays (8, [])!
    
    Call 4: getCell("K2") -> 8                            -> returns 8
    Call 5: getCell("K1") -> 8 + 0 = 8 (K3 unassigned)    -> returns 8
    
    Call 6: setCell("K3", 5)
      parsed = (5, []), _reaches_target([], "K3") -> False
      formulas["K3"] = (5, [])                            -> returns True
    
    Call 7: getCell("K1") -> 8 + 5 = 13                   -> returns 13
    
    Final output: [True, True, False, 8, 8, True, 13]
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Formula: (constant_sum, referenced_cells)
    #   6             -> (6, [])
    #   "R1 + S1 + 3" -> (3, ["R1", "S1"])
    #   "R1 + R1"     -> (0, ["R1", "R1"])
    Formula = Tuple[int, List[str]]
    
    
    def is_integer_literal(term: str) -> bool:
        """Return True if `term` is an optional +/- sign followed by digits."""
        if term.startswith("-") or term.startswith("+"):
            term = term[1:]
        return len(term) > 0 and term.isdigit()
    
    
    def parse_formula(value: object) -> Formula:
        """Convert an integer or formula string into (constant_sum, referenced_cells)."""
        if isinstance(value, int):
            return value, []
    
        text = str(value).strip()
        if text.startswith("="):
            text = text[1:]
    
        constant_sum = 0
        referenced_cells: List[str] = []
        for raw_part in text.split("+"):
            term = raw_part.strip()
            if not term:
                continue
            if is_integer_literal(term):
                constant_sum += int(term)
            else:
                # Keep a list (not a set) so "A1 + A1" counts A1's value twice.
                referenced_cells.append(term)
        return constant_sum, referenced_cells
    
    
    class Spreadsheet:
        def __init__(self) -> None:
            # self.formulas: maps cell_name -> (constant_sum, referenced_cells),
            # e.g. {"R1": (6, []), "T1": (3, ["R1", "S1"])}
            self.formulas: Dict[str, Formula] = {}
    
        def set_cell(self, cell: str, value: object) -> bool:
            """Save the parsed formula, or return False without changing anything if it creates a cycle."""
            constant_sum, referenced_cells = parse_formula(value)
    
            # Phase 1: check for a cycle BEFORE mutating self.formulas so a rejected write
            # leaves the existing spreadsheet untouched with nothing to roll back.
            if self._reaches_target(referenced_cells, cell):
                return False
    
            # Phase 2: store the new formula (overwriting automatically drops any old references).
            self.formulas[cell] = (constant_sum, referenced_cells)
            return True
    
        def get_cell(self, cell: str) -> int:
            """Evaluate `cell` from the current formulas; unassigned cells default to 0."""
            # computed_values: per-read memo table mapping cell_name -> evaluated int,
            # e.g. {"R1": -2, "S1": 9}, so shared inputs like X1 = X0 + X0 evaluate X0 once.
            computed_values: Dict[str, int] = {}
    
            # eval_stack: explicit call stack of cell names waiting to be evaluated,
            # avoiding Python's ~1000-frame recursion limit on deep chains.
            eval_stack: List[str] = [cell]
    
            while eval_stack:
                current = eval_stack[-1]
                if current in computed_values:
                    eval_stack.pop()
                    continue
    
                # Unassigned cells are missing from self.formulas and fall back to (0, []).
                constant_sum, referenced_cells = self.formulas.get(current, (0, []))
                missing_inputs: List[str] = []
                for ref in referenced_cells:
                    if ref not in computed_values:
                        missing_inputs.append(ref)
    
                if missing_inputs:
                    # Leave `current` on the stack and push its missing inputs above it
                    # so all inputs finish before we return to `current`.
                    eval_stack.extend(missing_inputs)
                    continue
    
                total = constant_sum
                for ref in referenced_cells:
                    total += computed_values[ref]
                computed_values[current] = total
                eval_stack.pop()
    
            return computed_values[cell]
    
        def _reaches_target(self, start_cells: List[str], target_cell: str) -> bool:
            """Return True if `target_cell` is in `start_cells` or reachable via their formula inputs."""
            # visited: set of cell names already expanded during this graph search
            visited: Set[str] = set()
            stack: List[str] = list(start_cells)
    
            while stack:
                current = stack.pop()
                # Checking `current == target_cell` right away catches self-loops (A1 = A1 + 1)
                # and stops before expanding target_cell's old formula, avoiding false cycles.
                if current == target_cell:
                    return True
                if current in visited:
                    continue
                visited.add(current)
    
                _, next_refs = self.formulas.get(current, (0, []))
                stack.extend(next_refs)
    
            return False
    
    
    def apply_spreadsheet_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
        sheet = Spreadsheet()
        results: List[object] = []
        for op, args in zip(operations, arguments):
            if op == "setCell":
                cell_name = str(args[0])
                results.append(sheet.set_cell(cell_name, args[1]))
            elif op == "getCell":
                cell_name = str(args[0])
                results.append(sheet.get_cell(cell_name))
            else:
                raise ValueError("unknown operation: " + op)
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of each spreadsheet cell as a recipe card rather than a pre-cooked dish. Instead of re-cooking every dependent dish whenever one ingredient changes, we simply file away each cell's recipe on setCell and sum the ingredients fresh whenever someone calls getCell (lazy evaluation, meaning we defer computing a number until someone actually requests it). Because every accepted write checks for loops beforehand, the recipes always form a directed acyclic graph (DAG)—a network of one-way dependency arrows with zero circular loops.

A naive recursive getCell that re-evaluates every referenced cell from scratch fails in two ways. First, if X1 = X0 + X0, X2 = X1 + X1, and so on for 60 levels, plain recursion recomputes X0 2^60 times—quadrillions of redundant calls—and a 1500-cell chain hits Python's ~1000-frame call-stack limit. Second, if setCell overwrites a cell before checking for circular references, a rejected write can erase the cell's prior formula or trap future reads in an infinite loop. We prevent both issues by checking reachability before saving a formula, and by evaluating reads with an explicit stack plus memoization (caching each cell's evaluated integer in a per-read dictionary so it is computed at most once per getCell call).

Walk through Examples 1 and 2 in miniature:

  1. setCell("R1", 6) stores "R1" -> (6, []), and setCell("T1", "R1 + S1 + 3") verifies neither "R1" nor "S1" reaches "T1", storing "T1" -> (3, ["R1", "S1"]).
  2. getCell("T1") pushes "T1" onto the evaluation stack, evaluates "S1" -> 0 (unassigned) and "R1" -> 6, and sums 3 + 6 + 0 = 9. Updating S1 = 9 and R1 = -2 immediately makes the next getCell("T1") return 3 + (-2) + 9 = 10.
  3. In Example 2 (K2 = 8, K1 = "K2 + K3"), trying setCell("K2", "K1 + 4") runs a depth-first search (DFS)—a graph walk following dependency arrows via a stack—from "K1", sees "K1" reads "K2", and immediately returns False while leaving K2 at 8.

Complexity

For a cell c, let U be the number of cells that c depends on (directly or indirectly, including c itself), and let R be the total number of cell-reference terms across the formulas of those U cells.

  • getCell time — O(U + R): Because the graph has no cycles and computed_values remembers every finished cell, each of the U reachable cells has its reference list scanned once to push missing inputs and once to sum their values, while any duplicate stack entries pop immediately in O(1) time.
  • setCell time — O(L + U_refs + R_refs): Splitting and parsing the input takes O(L) time where L is the formula string length, and the cycle-check DFS visits each unique cell U_refs and reference R_refs reachable from the new inputs at most once via the visited set.
  • Space — O(C + R_total) persistent, plus O(U + R) temporary: self.formulas stores one tuple per assigned cell (C cells) and every reference across all formulas (R_total references), while getCell and setCell allocate per-call stacks and dictionaries proportional to the reachable subgraph.

Edge cases

  • Unassigned cells: Reading a cell that was never set returns 0, and referencing an unassigned cell inside a formula (such as S1 in Example 1) contributes 0 until that cell is later assigned.
  • Direct self-reference: setCell("R1", "R1 + 1") puts "R1" directly into start_cells, so _reaches_target spots current == target_cell on the first pop and returns False.
  • Rejected write preserves old state: Because cycle detection runs before self.formulas[cell] is modified, a rejected update (like setCell("K2", "K1 + 4") in Example 2) leaves the cell's previous value (8) intact.
  • Overwriting a formula drops old links: Replacing B1 = "A1 + 1" with B1 = 10 overwrites self.formulas["B1"], so a subsequent A1 = "B1" no longer forms a cycle and succeeds.
  • Duplicate references in one formula: "R1 + R1 + R1" keeps ["R1", "R1", "R1"] as a list rather than a set, counting R1 three times during summation while still computing R1 only once.
  • Formatting variations: Negative integers (-2), constant-only strings ("5 + 6"), missing spaces ("R1+S1"), and optional leading "=" signs all parse cleanly.
  • Deep chains and diamond graphs: Iterative stack evaluation with computed_values handles 1500-cell chains without recursion errors and 60-level doubling ladders (2^60) in milliseconds.

Common mistakes

  • Plain recursion without memoization: Evaluating X(i) = X(i - 1) + X(i - 1) recursively without caching computed values triggers 2^(n + 1) - 1 calls and times out for n = 60.
  • Using call-stack recursion on long chains: Even with @lru_cache or a dictionary memo, recursive calls on a 1500-cell chain raise RecursionError in Python.
  • Mutating self.formulas before checking for a cycle: Writing the new formula first and forgetting to restore the old formula (or delete the key if the cell was previously unassigned) corrupts the sheet on rejected writes.
  • Walking dependencies in the wrong direction: To test whether cell = ... + ref creates a loop, you must check whether ref already depends on cell (walking outgoing formula inputs from ref toward cell), not the reverse.
  • Storing references in a set: Deduplicating referenced_cells turns "R1 + R1" into "R1", halving the result.

Alternative approaches

  • Eager evaluation on writes: Maintain both each cell's current integer value and a reverse map dependents[x] listing all cells whose formulas read x. On setCell(cell, value), walk dependents from cell to find all downstream affected cells, reject if any new reference lies in that set, and otherwise recompute those affected cells in topological order (an ordering where every input cell is updated before any formula that reads it). This makes getCell O(1) and wins when reads vastly outnumber writes.
  • Lazy evaluation with dirty flags: Cache computed cell values across reads, and on setCell walk downstream dependents to mark them with a dirty flag (a boolean marker meaning "my cached value is out of date and must be recomputed on the next read"). Reads recompute only dirty cells and reuse clean cached values, balancing write and read costs.

Follow-up questions

  • How would you extend the parser and evaluator to handle subtraction, multiplication, and parenthesized sub-expressions? Replace text.split("+") with a tokenizer and a small recursive-descent or shunting-yard parser that converts the formula string into an expression tree whose leaves are integer constants and cell labels. Cycle detection stays identical—simply collect every cell label appearing in the tree as referenced_cells—and get_cell evaluates a cell's expression tree once all of its referenced leaf cells are present in computed_values.
  • If reads outnumber writes by three orders of magnitude, how would you redesign storage so getCell runs in O(1) time? Switch from pure lazy evaluation to eager evaluation (or lazy caching with dirty flags). Maintain a reverse dependents adjacency map alongside each cell's current integer value; whenever setCell accepts a write, gather all downstream dependents and recompute them once in topological order so every getCell becomes a single O(1) dictionary lookup.
  • When setCell rejects an update due to a circular reference, how could you return the exact sequence of cells forming the cycle? Have _reaches_target record a parent: Dict[str, Optional[str]] map storing which cell pushed each visited cell onto the search stack. The instant current == target_cell, walk parent pointers backward to the starting reference in referenced_cells, reverse that path, and wrap it with target_cell at both ends (for example, K2 -> K1 -> K2).

Follow-up questions

Similar questions

More Harvey interview questions

All 46 Harvey questions →