Spreadsheet Cells With Sum Formulas and Loop Detection
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a command list on a spreadsheet whose cells hold integers or two-reference sum formulas, evaluating lazily and reporting circular references.
Spreadsheet Command Simulator
You are given a log of commands to run against an initially empty spreadsheet. Each cell stores a text value that is either a plain integer or a sum formula. Return what each command produces.
Commands
The two parallel lists operations and arguments describe the log. The command at index i has the name operations[i] and the argument list arguments[i].
"set_cell"with arguments[cell_id, value]: store the textvaluein the cellcell_id, replacing any earlier content. Nothing is evaluated at this point. The result for this command isNone."get_value"with arguments[cell_id]: compute the integer value of that cell. The result is that integer, or the string"ValueError"if the evaluation fails (see below).
The output list has one entry per command, in order.
How a cell is evaluated
- Never set: a cell that has not been set evaluates to
0. - Plain integer: if the stored text does not start with
=, convert it with Python'sint(...). If the conversion fails, the evaluation fails. - Formula: if the stored text starts with
=, it must match exactly=X+Y, whereXandYare each one uppercase letter followed by one or more digits (for example=A1+B10). The value is the value ofXplus the value ofY, each evaluated by these same rules. Any other formula text is invalid, and the evaluation fails. For example,=B1has only one reference and is invalid, and so is a formula with spaces. - Circular reference: if, while evaluating a cell, you come back to a cell that is still being evaluated higher up the chain, the evaluation fails. This includes a cell that refers to itself.
- Shared dependencies are not cycles: a cell may be reached by several different paths, as in
D = B + Cwhere bothBandCuseA. This is fine, because only a cell that is still in progress counts as a loop.
If any cell reached during a get_value fails, the whole get_value returns "ValueError". A failure in one query does not affect later commands. Cells may be overwritten freely, and a later get_value uses the current contents.
Task
Implement the function that runs all commands and returns the list of results. Each entry is None for set_cell, an int for a successful get_value, or the string "ValueError" for a failed get_value.
Constraints
- Cell IDs are an uppercase letter followed by a number, from
A1toZ99. operationsandargumentshave the same length, and every operation is"set_cell"or"get_value".- Referenced cells that were never set count as
0. - A cell's dependency chain can be up to a few thousand cells long, so avoid solutions that overflow the recursion limit or take exponential time on shared dependencies.
Examples
Example 1
Input: run_sheet_commands(['set_cell', 'set_cell', 'set_cell', 'get_value', 'set_cell', 'set_cell', 'get_value'], [['A1', '10'], ['B1', '20'], ['C1', '=A1+B1'], ['C1'], ['A1', '=B1'], ['B1', '=A1'], ['A1']])
Output: [None, None, None, 30, None, None, 'ValueError']
Hints
Hint 1
Store the raw text for each cell in a dictionary and evaluate only when a get_value command arrives.
Hint 2
Use a depth-first evaluation with a set of cells currently being evaluated. Seeing a cell already in that set means a circular reference. Remove a cell from the set once it finishes, so shared dependencies are not mistaken for cycles.
Hint 3
Match each formula against the exact pattern for two references, and treat anything else as an error. Within one query, cache finished cells so repeated shared dependencies are not re-evaluated, and raise the recursion limit for long chains.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the spreadsheet as a directed graph where each cell points to the cells its formula references. set_cell only records the raw text. All the work happens in get_value, which runs a depth-first evaluation.
For one query:
- If the cell is currently in the
visitingset, we have returned to a cell that is still being computed, so there is a circular reference and we raiseValueError. - Look up the stored text. A cell that was never set counts as
"0". - If the text does not start with
=, convert it withint. A bad conversion raisesValueErrorby itself. - Otherwise match the text against
=X+Ywith the two-reference pattern. If it does not match, raiseValueError. - Add the cell to
visiting, evaluate both references recursively, then remove the cell in afinallyblock. Store the sum in a per-query cache.
The top level catches ValueError and records "ValueError" in the result list. set_cell records None.
Why it is correct
- A cell is in
visitingonly while its own evaluation is on the call stack. Reaching it again means a path from the cell back to itself exists, which is exactly a circular reference. Self-reference is the shortest such loop. - Cells are removed from
visitingwhen they finish, so a diamond shape (two paths into the same cell) is not mistaken for a cycle. - The per-query cache only holds cells that finished successfully, so reusing them gives the same values as re-evaluating. It stops shared dependencies from causing exponential repeated work.
- Evaluation is lazy and uses the current text of each cell. Overwriting a cell, including one that was part of a loop, takes effect on the next
get_value. - Any failure, whether a loop, an invalid formula or a non-integer raw value, propagates up and makes the whole query return
"ValueError".
Complexity
Let V be the number of cells reachable from the queried cell. Each get_value is O(V) time and space, including the recursion depth. set_cell is O(1). Over the whole log, the cost is the sum of these per-query costs.
Reference solution
import re
import sys
from typing import List, Optional, Union
sys.setrecursionlimit(20000)
_FORMULA = re.compile(r"=([A-Z][0-9]+)\+([A-Z][0-9]+)")
def run_sheet_commands(operations: List[str], arguments: List[List[str]]) -> List[Optional[Union[int, str]]]:
cells = {}
results = []
def get_value(start):
visiting = set()
done = {}
def evaluate(cell):
if cell in visiting:
raise ValueError("Circular dependency")
if cell in done:
return done[cell]
text = cells.get(cell, "0")
if not text.startswith("="):
done[cell] = int(text)
return done[cell]
match = _FORMULA.fullmatch(text)
if match is None:
raise ValueError("Invalid formula")
visiting.add(cell)
try:
total = evaluate(match.group(1)) + evaluate(match.group(2))
finally:
visiting.remove(cell)
done[cell] = total
return total
return evaluate(start)
for operation, args in zip(operations, arguments):
if operation == "set_cell":
cells[args[0]] = args[1]
results.append(None)
elif operation == "get_value":
try:
results.append(get_value(args[0]))
except ValueError:
results.append("ValueError")
else:
raise ValueError("Unknown operation")
return results