In-Memory Spreadsheet with Formula Evaluation and Cycle Detection
Data Structure DesignAuto-graded · 16 test casesLast updated
Build a spreadsheet system that stores values, evaluates formulas referencing other cells, and prevents circular dependencies through pre-write validation.
Design and implement an in-memory spreadsheet system. Each cell is identified by a coordinate string combining column letters and row numbers (for example, A1, B2, or Z99).
Your implementation must handle three types of operations through a single function that processes batches of commands:
Operation Types:
-
set - Assigns a value or formula to a cell
- Arguments:
[cell_name, content] - Returns
1if successful,0if the operation was rejected
- Arguments:
-
get - Retrieves the computed value of a cell
- Arguments:
[cell_name] - Returns the integer value of the cell
- Arguments:
Value Format:
- Plain integer: A string representing a number like
"42"or"100" - Formula: A string beginning with
=followed by an expression that adds cell references and integer constants using the+operator- Example:
"=A1+B2+5"means add the value in A1, the value in B2, and the constant 5 - Formulas may reference cells that haven't been assigned yet
- Example:
Behavior Requirements:
- Cells that have never been assigned default to
0 - When evaluating a formula, use the current values of all referenced cells
- Formulas may reference other cells containing formulas, creating dependency chains
- Cycle Prevention: If assigning a value to a cell would create a circular dependency (where a cell depends on itself either directly or through intermediate cells), reject the entire operation and leave the spreadsheet completely unchanged
- Return
0for rejected set operations - Return
1for successful set operations
- Return
Constraints:
- Cell names match the pattern: one or more uppercase letters followed by a positive integer (row numbers start at 1)
- Formula expressions contain only cell references, integer constants, and the
+operator - All operations are processed sequentially in the order given
- 1 ≤ number of operations ≤ 1000
- 0 ≤ integer values ≤ 10^6
Examples
Example 1
Input: process_spreadsheet_commands(['set', 'set', 'get', 'set', 'get', 'set', 'get'], [['A1', '5'], ['B1', '=A1+3'], ['B1'], ['A1', '10'], ['B1'], ['C1', '=B1+A1+2'], ['C1']])
Output: [1, 1, 8, 1, 13, 1, 25]
Hints
Hint 1
Track which cells each formula depends on so you can detect cycles before committing a write
Hint 2
When checking for cycles, traverse the dependency graph starting from the cells that would depend on the cell being written
Hint 3
Store both the raw input (the string) and the parsed representation to avoid re-parsing on every read
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains two core data structures:
- Cell storage (
cell_data): Maps cell names to their content — either a plain integer or a parsed formula representation - Dependency tracker (
dependency_map): Maps each cell to the list of cells it directly references
Parsing: When content begins with =, extract tokens (cell references and integers) using regex. Validate that the formula consists only of these tokens separated by +. Store formulas as lists of (type, value) pairs.
Evaluation: To compute a cell's value, check if it stores an integer (return it) or a formula (recursively evaluate each referenced cell and sum the results). Unset cells default to zero. Track the evaluation path to detect cycles during reads, though this is only for safety since writes already prevent cycles.
Cycle detection: Before committing a set operation that introduces dependencies, perform a graph traversal starting from the cells that the target cell would reference. If this traversal reaches the target cell itself, a cycle would be created. Reject the write by returning 0 and leaving all state unchanged.
Correctness: The dependency map is updated atomically with each successful write, ensuring it always reflects current references. Cycle detection examines the full transitive closure of dependencies before any modification occurs.
Complexity
-
Time:
setwith a plain integer: O(1)setwith a formula: O(D) for parsing + O(V + E) for cycle detection, where D is the number of dependencies, V is the number of cells, and E is the total dependency edgesget: O(D) where D is the depth of the dependency chain for the requested cell
-
Space: O(N + E) where N is the number of cells with assigned values and E is the total number of dependency relationships
import re
from typing import List, Optional
def process_spreadsheet_commands(operations: List[str], arguments: List[List[str]]) -> List[Optional[int]]:
cell_data = {}
dependency_map = {}
valid_cell = re.compile(r"[A-Z]+[1-9][0-9]*")
token_finder = re.compile(r"[A-Z]+[1-9][0-9]*|[0-9]+")
def parse_input(content):
if not content.startswith("="):
return int(content), []
formula_body = content[1:]
tokens = token_finder.findall(formula_body)
if not tokens or "+".join(tokens) != formula_body:
raise ValueError("malformed formula")
parsed_terms = []
referenced_cells = []
for token in tokens:
if token[0].isalpha():
if not valid_cell.fullmatch(token):
raise ValueError("invalid cell name")
parsed_terms.append(("ref", token))
referenced_cells.append(token)
else:
parsed_terms.append(("val", int(token)))
return parsed_terms, referenced_cells
def compute_value(target_cell, active_path=None):
if target_cell not in cell_data:
return 0
stored = cell_data[target_cell]
if isinstance(stored, int):
return stored
if active_path is None:
active_path = set()
if target_cell in active_path:
raise ValueError("circular dependency")
active_path.add(target_cell)
total = sum(compute_value(ref, active_path) if typ == "ref" else ref
for typ, ref in stored)
active_path.remove(target_cell)
return total
output = []
for op, args in zip(operations, arguments):
if op == "get":
output.append(compute_value(args[0]))
continue
target, content = args
parsed_value, deps = parse_input(content)
if isinstance(parsed_value, list):
to_check = list(deps)
visited = set()
has_cycle = False
while to_check:
current = to_check.pop()
if current == target:
has_cycle = True
break
if current in visited:
continue
visited.add(current)
to_check.extend(dependency_map.get(current, ()))
if has_cycle:
output.append(0)
continue
cell_data[target] = parsed_value
dependency_map[target] = deps if isinstance(parsed_value, list) else []
output.append(1)
return output