In-Memory Spreadsheet Engine with Formulas and Cycle Handling

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Design an in-memory spreadsheet engine over a grid of cells and expose it through:

def spreadsheet_operations(
    operations: List[str], arguments: List[List]
) -> List[Optional[int]]:

Every cell coordinate consists of one uppercase column letter 'A' through 'Z' followed immediately by a 1-based row number 1 through 1000 (such as 'A1', 'D15', or 'Z1000'). Any cell that has never been written holds 0 by default.

Process the commands in operations alongside their matching parameter lists in arguments, returning a list with one result per command:

  1. "SET" with [cell, value]

    • Store literal integer value inside cell, discarding any prior number or formula stored there.
    • Propagate the change to every cell whose formula depends on cell directly or through intermediate cells.
    • Return value.
  2. "GET" with [cell]

    • Return the current evaluated integer value of cell (or None if cell is currently in an error state caused by a circular dependency).
  3. "SUM" with [cell, refs]

    • Store a live sum formula in cell (replacing any prior number or formula) over the reference strings in refs.
    • Each element of refs is either a single coordinate (such as 'B2') or an inclusive rectangular block 'X1:Y2' covering every column between 'X' and 'Y' and every row between 1 and 2.
    • If a cell appears multiple times across refs (either listed repeatedly or covered by overlapping blocks), include its value once per occurrence. An empty refs list evaluates to 0.
    • Propagate the updated result to downstream dependent cells and return cell's evaluated total (or None on a cycle).

Dependency & Cycle Semantics

  • Overwriting a formula cell via "SET" or a new "SUM" removes its old incoming dependencies so changes to previously referenced cells no longer affect it.
  • If a "SUM" command introduces a circular reference loop (for example, a cell referencing itself, or A2 referencing B2 while B2 references A2), the new formula is still stored in cell. Every cell on a cycle — and every cell whose formula directly or transitively reads a cyclic cell — evaluates to None. If a later "SET" or "SUM" breaks the cycle, affected cells automatically recover valid integer values.
  • Keep "GET" fast rather than re-walking large unchanged dependency chains from scratch on every read.

Examples

Example 1

Input:
  operations = ["SET", "SET", "SUM", "SET", "SUM", "SET", "GET", "GET"]
  arguments  = [
    ["A1", 3],
    ["B2", 4],
    ["C1", ["A1:B2", "B2"]],
    ["C1", 10],
    ["D1", ["C1", "A1"]],
    ["A1", 6],
    ["C1"],
    ["D1"]
  ]

Output:
  [3, 4, 11, 10, 13, 6, 10, 16]

Walk-through: After A1 = 3 and B2 = 4, SUM("C1", ["A1:B2", "B2"]) adds the four cells in A1:B2 (3 + 0 + 0 + 4 = 7) plus the extra "B2" (4) to produce 11. Next, SET("C1", 10) overwrites C1's formula with the plain integer 10, and SUM("D1", ["C1", "A1"]) evaluates to 10 + 3 = 13. When A1 changes to 6, C1 stays 10 because its formula was replaced, while D1 updates to 10 + 6 = 16.

Example 2

Input:
  operations = ["SET", "SUM", "SUM", "SET", "GET"]
  arguments  = [
    ["B1", 5],
    ["B2", ["B1"]],
    ["B3", ["B1:B2"]],
    ["B1", -2],
    ["B3"]
  ]

Output:
  [5, 5, 10, -2, -4]

Walk-through: Initially B1 = 5, B2 = 5, and B3 = B1 + B2 = 10. Updating B1 to -2 cascades through B2 (-2) into B3 (-2 + -2 = -4).

Example 3

Input:
  operations = ["GET", "SUM", "GET"]
  arguments  = [["Z999"], ["M10", []], ["M10"]]

Output:
  [0, 0, 0]

Walk-through: Reading an untouched cell (Z999) yields 0, and summing an empty list of references ([]) also evaluates to 0.

Example 4

Input:
  operations = ["SET", "SUM", "SUM", "GET", "SET", "GET"]
  arguments  = [
    ["A2", 7],
    ["B2", ["A2"]],
    ["A2", ["B2"]],
    ["B2"],
    ["A2", 9],
    ["B2"]
  ]

Output:
  [7, 7, None, None, 9, 9]

Walk-through: Defining A2 = SUM(["B2"]) while B2 = SUM(["A2"]) forms a two-cell loop, so both A2 and B2 become None. Later, SET("A2", 9) replaces A2's formula with literal 9, breaking the loop so B2 recovers to 9.

Constraints

  • Column identifiers are single uppercase ASCII letters 'A' through 'Z' (26 columns).
  • Row identifiers are integers 1 through 1000 (1,000 rows, up to 26,000 cells total).
  • len(operations) == len(arguments)
  • Cell values set via "SET" are signed integers (positive, zero, or negative).
  • Every coordinate in arguments and inside refs lies within 'A1' .. 'Z1000'.

Step-by-step walkthrough

  1. Understand the operations and rules

    We need to build an in-memory spreadsheet over columns 'A' through 'Z' and rows 1 through 1000 (26,000 possible cells such as 'A1', 'B2', and 'Z1000'). The judge calls spreadsheet_operations(operations, arguments) and expects one return value per operation:

    • SET(cell, value): store plain integer value in cell, erasing any previous value or formula there, and return value.
    • GET(cell): return the current evaluated value of cell.
    • SUM(cell, refs): store a live sum formula in cell over refs (where each item is a single cell 'B2' or a rectangular range 'A1:B2'), and return its evaluated value.

    Looking closely at the examples reveals three important rules:

    1. Unset cells equal 0: Example 3 shows GET('Z999') == 0 and SUM('M10', []) == 0.
    2. Duplicate references add multiple times: In Example 1 (A1 = 3, B2 = 4), SUM('C1', ['A1:B2', 'B2']) returns 11, because B2 appears once inside 'A1:B2' and a second time explicitly (3 + 0 + 0 + 4 + 4 = 11).
    3. Cycles store the formula and evaluate to None: In Example 4 (A2 = 7, B2 = SUM(['A2'])), calling SUM('A2', ['B2']) returns None, and GET('B2') afterward also returns None. When SET('A2', 9) later breaks the loop, B2 automatically recovers to 9.
  2. Why evaluating from scratch on every GET falls short

    The simplest idea is to store raw formulas and recursively evaluate a cell's references every time GET is called. That breaks down in three ways:

    • Repeated work: In a long chain A1 -> A2 -> ... -> Z1000, every GET('Z1000') walks all 26,000 cells again even when nothing changed, making reads painfully slow.
    • Stack overflow: A 26,000-cell chain is far deeper than Python's default recursion limit (~1,000 frames) and raises RecursionError.
    • Infinite loops on cycles: If A2 sums B2 and B2 sums A2, naive recursion bounces back and forth forever.
  3. Key idea: reverse dependencies and topological recalculation

    Instead of recomputing on GET, we keep every cell's evaluated value cached so GET is an instant O(1) dictionary lookup. Whenever SET or SUM modifies a cell start, we recompute only start and the cells whose formulas depend on start (directly or through a chain).

    To find those downstream cells quickly, we store edges in both directions:

    • formulas[cell]: what cell reads ({ref_cell: multiplicity}).
    • dependents[ref]: which formula cells read ref (reverse edges / subscribers).

    Be careful about the order in which we recompute affected cells! Look at this diamond-shaped graph when A1 changes:

          A1 (changed!)
         /  \
        v    \
       B1     |
        \     |
         v    v
       C1 --> D1 = C1 + A1
    

    If we simply recomputed cells in breadth-first order from A1, D1 is 1 hop from A1 while C1 is 2 hops (A1 -> B1 -> C1), so D1 would be recomputed before C1 got its new value!

    We solve both evaluation order and cycle detection at once with Kahn's topological sort restricted to the affected set:

    1. Collect affected: Follow dependents arrows starting at start to gather every cell reachable downstream.
    2. Count waiting[cell]: For each cell in affected, count how many of its distinct formula references are also in affected (references outside affected did not change, so their cached values are already up to date).
    3. Process ready cells (waiting == 0): Pop a ready cell from a queue, compute its new value from its references, and decrement waiting on each of its affected dependents — pushing any dependent whose waiting hits 0.
    4. Spot cycles (waiting > 0 left over): Cells in a cycle wait on each other in a loop, so their waiting counts never hit 0 (and neither do cells waiting on that cycle). Setting every leftover cell with waiting[cell] > 0 to None catches all cycles automatically!
  4. Parse cell coordinates and expand ranges

    A cell ID like 'B12' has a single uppercase column letter (cell_id[0]) followed by an integer row (int(cell_id[1:])). A range 'A1:B2' expands across every column code from 'A' to 'B' and every row from 1 to 2.

    In expand_refs, we accumulate {cell: count} rather than a plain set. That way, ['A1:B1', 'B1'] becomes {'A1': 1, 'B1': 2}: B1's value is multiplied by 2 during evaluation, while we only store one reverse edge per distinct cell!

    from collections import deque
    
    
    def parse_cell(cell_id: str) -> Tuple[str, int]:
        """Split `'B12'` into its column letter `'B'` and integer row `12`."""
        col_letter = cell_id[0]
        row_number = int(cell_id[1:])
        return col_letter, row_number
    
    
    def cells_in_range(first: str, last: str) -> List[str]:
        """List every cell ID inside the inclusive rectangle between `first` and `last`."""
        first_col, first_row = parse_cell(first)
        last_col, last_row = parse_cell(last)
    
        # Using min/max handles ranges even if corners are given in non-top-left order
        start_col_ord = ord(min(first_col, last_col))
        end_col_ord = ord(max(first_col, last_col))
        start_row = min(first_row, last_row)
        end_row = max(first_row, last_row)
    
        cells: List[str] = []
        for col_ord in range(start_col_ord, end_col_ord + 1):
            col_letter = chr(col_ord)
            for row_num in range(start_row, end_row + 1):
                cells.append(f"{col_letter}{row_num}")
        return cells
    
    
    def expand_refs(refs: List[str]) -> Dict[str, int]:
        """Count how many times each cell is referenced across `refs`, expanding `'A1:B2'` ranges."""
        # counts: Dict[str, int] — e.g. ['A1:B1', 'B1'] -> {'A1': 1, 'B1': 2}
        counts: Dict[str, int] = {}
        for ref in refs:
            if ":" in ref:
                first, last = ref.split(":")
                expanded = cells_in_range(first, last)
            else:
                expanded = [ref]
            for cell in expanded:
                counts[cell] = counts.get(cell, 0) + 1
        return counts
    
  5. Store spreadsheet state and handle SET, GET, and SUM

    Whenever SET or SUM writes to cell, _clear_formula(cell) must first detach cell from the dependents sets of its old formula references. Otherwise, as seen in Example 1 when SET('C1', 10) replaces C1's old formula, changing A1 later would mistakenly wake up C1!

    In _evaluate(cell), if cell has no formula it simply returns self.values.get(cell, 0). Otherwise it sums ref_value * count across its references — returning None immediately if any referenced cell currently holds None (an upstream cycle error).

    class Spreadsheet:
        def __init__(self) -> None:
            # values: Dict[str, Optional[int]] — cached value per cell, e.g. {'A1': 10, 'B1': None}; unset -> 0
            self.values: Dict[str, Optional[int]] = {}
            # formulas: Dict[str, Dict[str, int]] — formula cell -> {ref_cell: count}, e.g. {'C1': {'A1': 1, 'B2': 2}}
            self.formulas: Dict[str, Dict[str, int]] = {}
            # dependents: Dict[str, Set[str]] — reverse edges: cell -> formula cells that directly reference it
            self.dependents: Dict[str, Set[str]] = {}
    
        def set_cell(self, cell: str, number: int) -> int:
            # Overwriting a cell must first remove any old formula and its reverse dependency edges
            self._clear_formula(cell)
            self.values[cell] = number
            self._recalculate(cell)
            return number
    
        def get_cell(self, cell: str) -> Optional[int]:
            # Missing keys were never set and default to 0; explicitly stored `None` (cycle error) is preserved
            return self.values.get(cell, 0)
    
        def sum_cells(self, cell: str, refs: List[str]) -> Optional[int]:
            self._clear_formula(cell)
            ref_counts = expand_refs(refs)
            self.formulas[cell] = ref_counts
    
            # Register reverse edges so changes to any `ref` notify `cell`
            for ref in ref_counts:
                if ref not in self.dependents:
                    self.dependents[ref] = set()
                self.dependents[ref].add(cell)
    
            self._recalculate(cell)
            return self.values[cell]
    
        def _clear_formula(self, cell: str) -> None:
            """Remove `cell`'s existing formula and detach `cell` from its old references' subscriber sets."""
            if cell not in self.formulas:
                return
            for old_ref in self.formulas[cell]:
                self.dependents[old_ref].discard(cell)
            del self.formulas[cell]
    
        def _evaluate(self, cell: str) -> Optional[int]:
            """Compute `cell`'s value once from the already-updated values of its direct references."""
            if cell not in self.formulas:
                return self.values.get(cell, 0)
    
            total = 0
            for ref, count in self.formulas[cell].items():
                ref_value = self.values.get(ref, 0)
                # If any referenced cell has a cycle error (`None`), that error propagates to `cell`
                if ref_value is None:
                    return None
                total += ref_value * count
            return total
    
  6. Recalculate affected cells with Kahn's algorithm

    Now we translate our 4-phase recalculation plan directly into iterative loops (no recursion, so 26,000-cell chains never hit a stack limit):

        def _recalculate(self, start: str) -> None:
            """Incrementally recompute `start` and all cells downstream of it in topological order."""
            # Phase 1: walk reverse edges (`dependents`) to collect `start` and all transitive dependents
            affected: Set[str] = {start}
            stack: List[str] = [start]
            while stack:
                current = stack.pop()
                for dep in self.dependents.get(current, ()):
                    if dep not in affected:
                        affected.add(dep)
                        stack.append(dep)
    
            # Phase 2: for each affected cell, count how many distinct affected cells its formula waits on
            # (references outside `affected` did not change, so their cached values are already valid)
            # ready: FIFO queue of affected cell IDs whose waiting count has reached 0
            waiting: Dict[str, int] = {}
            ready = deque()
            for cell in affected:
                in_degree = 0
                for ref in self.formulas.get(cell, {}):
                    if ref in affected:
                        in_degree += 1
                waiting[cell] = in_degree
                if in_degree == 0:
                    ready.append(cell)
    
            # Phase 3: Kahn's topological sort — evaluate a cell only after all affected inputs are ready
            while ready:
                cell = ready.popleft()
                self.values[cell] = self._evaluate(cell)
                for dep in self.dependents.get(cell, ()):
                    if dep in affected:
                        waiting[dep] -= 1
                        if waiting[dep] == 0:
                            ready.append(dep)
    
            # Phase 4: any affected cell whose `waiting` count never reached 0 is on or downstream of a cycle
            for cell in affected:
                if waiting[cell] > 0:
                    self.values[cell] = None
    
  7. Trace through Example 4 (cycle creation and recovery)

    Let's trace Example 4 (SET('A2', 7), SUM('B2', ['A2']), SUM('A2', ['B2']), GET('B2'), SET('A2', 9), GET('B2')):

    1. SET('A2', 7)
       affected = {'A2'}, waiting = {'A2': 0}, ready = ['A2']
       -> values['A2'] = 7
    
    2. SUM('B2', ['A2'])
       dependents['A2'] = {'B2'}
       affected = {'B2'}, waiting = {'B2': 0} ('A2' is NOT in affected, its cached 7 is valid!)
       -> values['B2'] = 7
    
    3. SUM('A2', ['B2'])     (closes cycle A2 <-> B2)
       dependents['B2'] = {'A2'}, dependents['A2'] = {'B2'}
       affected = {'A2', 'B2'}
       waiting  = {'A2': 1, 'B2': 1}, ready = []   (neither is 0!)
       Phase 4 sets both stuck cells to None -> values['A2'] = None, values['B2'] = None
    
    4. GET('B2') -> returns values['B2'] = None
    
    5. SET('A2', 9)          (breaks the cycle!)
       _clear_formula('A2') detaches 'A2' from dependents['B2']; dependents['A2'] still has {'B2'}
       affected = {'A2', 'B2'}
       waiting  = {'A2': 0, 'B2': 1}, ready = ['A2']
       Pop 'A2' -> values['A2'] = 9, decrements waiting['B2'] to 0 -> push 'B2'
       Pop 'B2' -> values['B2'] = 9   (both cells recover!)
    
    6. GET('B2') -> returns values['B2'] = 9
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def parse_cell(cell_id: str) -> Tuple[str, int]:
        """Split `'B12'` into its column letter `'B'` and integer row `12`."""
        col_letter = cell_id[0]
        row_number = int(cell_id[1:])
        return col_letter, row_number
    
    
    def cells_in_range(first: str, last: str) -> List[str]:
        """List every cell ID inside the inclusive rectangle between `first` and `last`."""
        first_col, first_row = parse_cell(first)
        last_col, last_row = parse_cell(last)
    
        # Using min/max handles ranges even if corners are given in non-top-left order
        start_col_ord = ord(min(first_col, last_col))
        end_col_ord = ord(max(first_col, last_col))
        start_row = min(first_row, last_row)
        end_row = max(first_row, last_row)
    
        cells: List[str] = []
        for col_ord in range(start_col_ord, end_col_ord + 1):
            col_letter = chr(col_ord)
            for row_num in range(start_row, end_row + 1):
                cells.append(f"{col_letter}{row_num}")
        return cells
    
    
    def expand_refs(refs: List[str]) -> Dict[str, int]:
        """Count how many times each cell is referenced across `refs`, expanding `'A1:B2'` ranges."""
        # counts: Dict[str, int] — e.g. ['A1:B1', 'B1'] -> {'A1': 1, 'B1': 2}
        counts: Dict[str, int] = {}
        for ref in refs:
            if ":" in ref:
                first, last = ref.split(":")
                expanded = cells_in_range(first, last)
            else:
                expanded = [ref]
            for cell in expanded:
                counts[cell] = counts.get(cell, 0) + 1
        return counts
    
    
    class Spreadsheet:
        """In-memory spreadsheet with eager incremental recalculation so `GET` is O(1).
    
        Cycle behavior:
        A `SUM` that introduces a cycle is still stored (overwriting the cell's old value/formula).
        Every cell on a cycle — and every cell whose formula transitively depends on a cycle —
        evaluates to `None`. If a later `SET` or `SUM` breaks the cycle, affected cells recover
        their numeric values automatically.
        """
    
        def __init__(self) -> None:
            # values: Dict[str, Optional[int]] — cached value per cell, e.g. {'A1': 10, 'B1': None}; unset -> 0
            self.values: Dict[str, Optional[int]] = {}
            # formulas: Dict[str, Dict[str, int]] — formula cell -> {ref_cell: count}, e.g. {'C1': {'A1': 1, 'B2': 2}}
            self.formulas: Dict[str, Dict[str, int]] = {}
            # dependents: Dict[str, Set[str]] — reverse edges: cell -> formula cells that directly reference it
            self.dependents: Dict[str, Set[str]] = {}
    
        def set_cell(self, cell: str, number: int) -> int:
            # Overwriting a cell must first remove any old formula and its reverse dependency edges
            self._clear_formula(cell)
            self.values[cell] = number
            self._recalculate(cell)
            return number
    
        def get_cell(self, cell: str) -> Optional[int]:
            # Missing keys were never set and default to 0; explicitly stored `None` (cycle error) is preserved
            return self.values.get(cell, 0)
    
        def sum_cells(self, cell: str, refs: List[str]) -> Optional[int]:
            self._clear_formula(cell)
            ref_counts = expand_refs(refs)
            self.formulas[cell] = ref_counts
    
            # Register reverse edges so changes to any `ref` notify `cell`
            for ref in ref_counts:
                if ref not in self.dependents:
                    self.dependents[ref] = set()
                self.dependents[ref].add(cell)
    
            self._recalculate(cell)
            return self.values[cell]
    
        def _clear_formula(self, cell: str) -> None:
            """Remove `cell`'s existing formula and detach `cell` from its old references' subscriber sets."""
            if cell not in self.formulas:
                return
            for old_ref in self.formulas[cell]:
                self.dependents[old_ref].discard(cell)
            del self.formulas[cell]
    
        def _evaluate(self, cell: str) -> Optional[int]:
            """Compute `cell`'s value once from the already-updated values of its direct references."""
            if cell not in self.formulas:
                return self.values.get(cell, 0)
    
            total = 0
            for ref, count in self.formulas[cell].items():
                ref_value = self.values.get(ref, 0)
                # If any referenced cell has a cycle error (`None`), that error propagates to `cell`
                if ref_value is None:
                    return None
                total += ref_value * count
            return total
    
        def _recalculate(self, start: str) -> None:
            """Incrementally recompute `start` and all cells downstream of it in topological order."""
            # Phase 1: walk reverse edges (`dependents`) to collect `start` and all transitive dependents
            affected: Set[str] = {start}
            stack: List[str] = [start]
            while stack:
                current = stack.pop()
                for dep in self.dependents.get(current, ()):
                    if dep not in affected:
                        affected.add(dep)
                        stack.append(dep)
    
            # Phase 2: for each affected cell, count how many distinct affected cells its formula waits on
            # (references outside `affected` did not change, so their cached values are already valid)
            # ready: FIFO queue of affected cell IDs whose waiting count has reached 0
            waiting: Dict[str, int] = {}
            ready = deque()
            for cell in affected:
                in_degree = 0
                for ref in self.formulas.get(cell, {}):
                    if ref in affected:
                        in_degree += 1
                waiting[cell] = in_degree
                if in_degree == 0:
                    ready.append(cell)
    
            # Phase 3: Kahn's topological sort — evaluate a cell only after all affected inputs are ready
            while ready:
                cell = ready.popleft()
                self.values[cell] = self._evaluate(cell)
                for dep in self.dependents.get(cell, ()):
                    if dep in affected:
                        waiting[dep] -= 1
                        if waiting[dep] == 0:
                            ready.append(dep)
    
            # Phase 4: any affected cell whose `waiting` count never reached 0 is on or downstream of a cycle
            for cell in affected:
                if waiting[cell] > 0:
                    self.values[cell] = None
    
    
    def spreadsheet_operations(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
        sheet = Spreadsheet()
        results: List[Optional[int]] = []
        for op, args in zip(operations, arguments):
            if op == "SET":
                results.append(sheet.set_cell(args[0], args[1]))
            elif op == "GET":
                results.append(sheet.get_cell(args[0]))
            elif op == "SUM":
                results.append(sheet.sum_cells(args[0], args[1]))
            else:
                raise ValueError(f"Unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the spreadsheet as a subscriber notification network — a directed graph (a collection of nodes connected by one-way arrows) where every cell keeps a subscriber list (dependents) of the formulas that read it. Whenever a cell changes via SET or SUM, it notifies all downstream subscribers. However, if cell D1 adds B1 + C1 and both B1 and C1 depend on A1, D1 must wait at the intersection until both B1 and C1 finish updating before computing its new sum. We enforce that rule with Kahn's algorithm — a queue-based topological sort (ordering nodes so every prerequisite comes before the nodes that use it) that tracks each affected cell's in-degree (how many affected inputs it is still waiting on) and evaluates a cell only when its wait count drops to 0. Better yet, cells trapped in a circular loop wait on each other forever, so their wait counts never hit 0 — exposing cycles automatically!

Evaluating formulas on demand during every GET fails because a 26,000-cell chain forces each GET to re-walk thousands of unchanged cells, overflows Python's recursion stack, and spins forever on cycles unless visited-path state is tracked. Conversely, pushing updates with a plain breadth-first search without waiting counts fails on diamond dependencies (A1 -> B1 -> C1 and D1 = A1 + C1), where D1 sits 1 hop from A1 and would read C1's stale value before C1 updates at hop 2.

Let's trace Example 2 (B1 -> B2 -> B3):

  • SET('B1', 5): affected = {'B1'}, waiting['B1'] = 0 -> values['B1'] = 5.
  • SUM('B2', ['B1']): B2 subscribes to B1. affected = {'B2'} (B1 did not change, so waiting['B2'] = 0) -> values['B2'] = 5.
  • SUM('B3', ['B1:B2']): B3 subscribes to B1 and B2 -> values['B3'] = 5 + 5 = 10.
  • SET('B1', -2): following subscribers from B1 gathers affected = {'B1', 'B2', 'B3'} with waiting = {'B1': 0, 'B2': 1, 'B3': 2}. B1 evaluates first (-2), dropping B2 to 0 and B3 to 1; then B2 evaluates (-2), dropping B3 to 0; finally B3 evaluates (-2 + -2 = -4). Every later GET is an instant dictionary lookup!

Complexity

Let A be the number of affected cells on an update (start plus its transitive dependents, meaning cells that depend on start directly or through intermediate formulas), F be the total number of distinct formula references across those A affected cells, L be the expanded cell count of refs in a SUM call (with duplicates), and P be the number of distinct references in any old formula overwritten on the target cell.

  • GET: O(1) time. Every cell's latest evaluated value (or None on a cycle) is kept cached in self.values, so GET does a single hash-map lookup.
  • SET: O(P + A + F) time. Clearing an overwritten formula removes P reverse edges in O(P); then collecting affected, counting waiting, and running Kahn's queue each touch the A affected cells and their F formula edges a constant number of times.
  • SUM: O(P + L + A + F) time. Expanding ranges visits L cell coordinates, registering reverse edges takes at most O(L), and _recalculate runs in O(A + F).
  • Space: O(C + E), where C is the number of cells written so far and E is the total number of distinct (formula_cell, referenced_cell) links stored once in self.formulas and once in self.dependents (plus O(A) temporary sets/queues during _recalculate).

Edge cases

  • Unset cells and empty formulas: GET('Z999') and SUM('M10', []) both evaluate to 0 because unset keys default to 0 via self.values.get(cell, 0).
  • Duplicate and overlapping references (['A1:B2', 'B2']): storing {cell: count} multiplies B2's value by 2 in _evaluate while adding 'C1' to dependents['B2'] once.
  • Self-loops (SUM('A1', ['A1']) or SUM('B2', ['A1:C3'])): waiting starts at 1 on that single cell, ready is empty, and Phase 4 marks it None.
  • Existing dependents of a newly formed cycle: if C1 = B1 + B1 already existed before A1 <-> B1 became a cycle, C1 is part of affected, never reaches waiting == 0, and turns into None too.
  • Partial and full cycle recovery: overwriting a cycle cell with SET (or a non-cyclic SUM) detaches the cyclic edge and runs _recalculate, restoring valid numbers to cells no longer downstream of any cycle while keeping cells on a separate remaining loop at None.
  • Overwriting a formula (SET after SUM, or SUM after SUM): _clear_formula removes old dependents entries so changes to previously referenced cells no longer trigger updates.

Common mistakes

  • Rejecting a cyclic SUM and keeping the previous value: Example 4 expects SUM('A2', ['B2']) and the subsequent GET('B2') to return None, not the old value 7.
  • Storing formula references as a set instead of {cell: count}: loses duplicate occurrences inside refs and returns 7 instead of 11 on Example 1's ['A1:B2', 'B2'].
  • Forgetting to remove reverse edges when overwriting a cell: leaves ghost entries in self.dependents, causing overwritten SET cells or updated SUM cells to be wrongly recalculated later.
  • Recomputing affected cells in plain BFS/DFS discovery order: evaluates downstream merge nodes in a diamond graph before all upstream branches have been updated, caching stale totals.
  • Using self.values.get(cell) or 0: in Python None or 0 evaluates to 0! You must check if ref_value is None: explicitly so cycle errors (None) are not silently turned into 0.

Alternative approaches

  • Lazy evaluation with dirty flags: Instead of recomputing values eagerly on every SET/SUM, mark start and its transitive dependents with a dirty flag (a boolean marker recording that a cached value is out of date, stopping traversal whenever an already-dirty cell is hit). Then GET(cell) evaluates dirty cells on demand using an iterative depth-first stack with a "currently on path" set to detect cycles, caching clean results for future GETs. Lazy invalidation shines when many SETs happen back-to-back before a single GET, at the cost of slower and more stateful GET calls.

Follow-up questions

  • How would your implementation change if a SUM command that creates a circular reference had to be rejected without modifying the sheet? Before mutating cell's formula in sum_cells, collect affected (all cells that currently depend on cell, including cell itself) by walking self.dependents from cell. A new formula on cell creates a cycle if and only if at least one of its expanded references is in affected (meaning ref already depends on cell, so cell -> ref would close a loop). If any ref in affected, return None (or raise an exception) immediately without touching self.formulas, self.dependents, or self.values.
  • Under what workload patterns would lazy dirty-bit invalidation outperform eager topological recalculation? Eager recalculation excels when reads (GET / UI renders) outnumber writes or when every edit immediately re-renders all visible dependent cells anyway. Lazy dirty-bit marking wins during bulk imports or batch scripts that execute thousands of SET calls before reading a few summary cells — marking an already-dirty subgraph stops in O(1) instead of recomputing the same downstream totals thousands of times.
  • How could you optimize formulas spanning huge rectangular blocks like B1:Z1000 when individual cells inside the block change frequently? Expanding 'B1:Z1000' creates 25,000 reverse edges and scans 25,000 entries per evaluation. Instead, maintain a 2D Fenwick tree (a compact grid data structure that updates one cell and sums any rectangular subgrid in O(log R * log C) time — roughly 5 * 10 = 50 operations on a 26 x 1000 sheet) for numeric cell values, plus a second 2D Fenwick tree counting how many cells currently hold None so any error inside the rectangle still evaluates to None, while storing range objects unexpanded rather than per-cell edges.

Follow-up questions

Similar questions

More Fuse Energy interview questions

All 2 Fuse Energy questions →