Cell Formula Evaluator with Cycle Detection
Trees & GraphsAuto-graded · 20 test casesLast updated
Build a mini spreadsheet engine that evaluates formulas, detects circular dependencies, and handles dynamic updates.
Build a spreadsheet evaluator that processes a sequence of commands to store and retrieve cell values. Cells can hold integers or formulas that reference other cells.
You will implement a function that takes a list of operations and returns a list of results, one per operation.
Operations
Each operation is a list with 2 or 3 elements:
["set", cell_id, content]: Storecontentin the cell identified bycell_id. Return"OK".["get", cell_id]: Compute and return the value of the cell. Return the value as a string in canonical decimal form (no leading zeros or plus signs; zero is"0"), or"CYCLE"if evaluation encounters a circular reference.
Cell Identifiers
Cell identifiers consist of one or more uppercase letters followed by a positive integer (no leading zeros). Examples: A1, Z99, AA10.
Cell Content
Content is either:
- A signed integer string (e.g.,
"5","-12","0") - A formula beginning with
=
Formula Syntax
A formula has the form term op term op term ... where:
- Each
termis either a non-negative integer literal or a cell identifier - Each
opis+or- - Whitespace may appear between tokens
Formulas do not support parentheses or unary operators inside the expression.
Evaluation Rules
- A cell that has never been set evaluates to
0 - Each reference to a cell in a formula contributes independently. For example,
=A1+A1adds the value ofA1twice. - When a cell is set, its previous content is completely replaced
- A
getoperation must detect if evaluating the target cell requires traversing a dependency cycle. If a cycle is encountered, return"CYCLE". - Cycles that are not reachable from the requested cell do not affect the result
- Setting a cell to a new value may create or break cycles; the next
getreflects the updated dependency graph
Constraints
- At most 500 operations
- At most 100 terms in any formula
- All numeric literals, stored integers, and intermediate arithmetic results fit in a signed 32-bit integer
- All inputs are syntactically valid
Examples
Example 1
Input: evaluate_sheet([['set', 'A1', '4'], ['set', 'B1', '=A1+A1-1'], ['get', 'B1'], ['set', 'A1', '8'], ['get', 'B1']])
Output: ['OK', 'OK', '7', 'OK', '15']
Example 2
Input: evaluate_sheet([['set', 'A1', '=B1+1'], ['set', 'B1', '=A1'], ['get', 'A1'], ['get', 'C1'], ['set', 'B1', '2'], ['get', 'A1']])
Output: ['OK', 'OK', 'CYCLE', '0', 'OK', '3']
Hints
Hint 1
Store each cell's raw content as-is and compute values on demand when a get is issued
Hint 2
Use depth-first traversal from the target cell through its dependencies; a cell visited while already being evaluated indicates a cycle
Hint 3
Track three states for each cell during evaluation: not yet seen, currently evaluating (on the recursion stack), and fully computed (memoized)
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to evaluate cells lazily on each get request using depth-first traversal through the dependency graph, where edges point from a formula to each cell it references. Maintain the raw content exactly as stored and recompute from scratch on every get to automatically handle dynamic updates and cycle changes.
During traversal, track each cell in one of three states:
- Unvisited (not in the state map): not yet encountered in this evaluation
- In-progress (state = 1): currently being evaluated; this cell is on the recursion stack
- Complete (state = 2): fully evaluated and memoized for this
get
When traversing dependencies, if we reach a cell that is in-progress, we have discovered a back-edge—a path from that cell to itself—which means a cycle exists. Raise an exception to abort with "CYCLE". If we reach a completed cell, return its memoized value immediately.
For formula parsing, use a single regex to tokenize the content after the = sign into cell references, integer literals, and operators. Walk the token list left-to-right, maintaining a pending sign (+1 or -1). When an operator token appears, update the sign. When a term token appears (cell reference or literal), evaluate or parse it, multiply by the sign, add to the running total, and reset the sign to +1.
Each reference in a formula is evaluated independently, so =A1+A1 calls compute(A1) twice. The second call hits the memoized value, making it O(1).
This approach correctly handles:
- Unset cells returning zero
- Self-references causing cycles
- Diamond dependencies (not cycles) via memoization
- Cycles elsewhere in the sheet not affecting unrelated cells
- Cycles appearing or disappearing when formulas change
Complexity
Time: O(Q · S) where Q is the number of operations and S is the total length of all stored content. Each get performs DFS over reachable cells, evaluating each at most once and scanning its tokens once. With Q ≤ 500 and formulas bounded by 100 terms, this is efficient.
Space: O(C) for storing C distinct cells' content, plus O(C) for state and memoization dictionaries during each get, plus O(D) recursion depth where D is the longest dependency chain.
Solution
import re
from typing import List
def evaluate_sheet(operations: List[List[str]]) -> List[str]:
storage = {}
output = []
token_regex = re.compile(r"[A-Z]+[1-9][0-9]*|[0-9]+|[+-]")
for op in operations:
if op[0] == "set":
storage[op[1]] = op[2]
output.append("OK")
continue
cell_target = op[1]
visit_state = {}
value_cache = {}
def compute(cell_id):
if cell_id not in storage:
return 0
if visit_state.get(cell_id) == 1:
raise ValueError("CYCLE")
if visit_state.get(cell_id) == 2:
return value_cache[cell_id]
visit_state[cell_id] = 1
content = storage[cell_id]
if not content.startswith("="):
val = int(content)
else:
val = 0
current_sign = 1
for tok in token_regex.findall(content[1:]):
if tok == "+":
current_sign = 1
elif tok == "-":
current_sign = -1
else:
term_val = compute(tok) if tok[0].isalpha() else int(tok)
val += current_sign * term_val
current_sign = 1
visit_state[cell_id] = 2
value_cache[cell_id] = val
return val
try:
output.append(str(compute(cell_target)))
except ValueError:
output.append("CYCLE")
return output