Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Cells store plain integer values, and formulas only add two operands that are either numbers or cell references. No dependency graph or formula propagation is needed: evaluating a formula simply reads the current stored values.
Approach
Allocate a zero-filled grid with 26 columns and one extra row so spreadsheet row numbers can be used directly. Decode a cell reference by converting its initial letter to a zero-based column and its remaining digits to the row number. setCell assigns the value, and resetCell assigns zero.
For getValue, remove the leading equals sign and split at the plus sign. Parse an all-digit operand as an integer; otherwise decode it as a cell reference and read the grid. Add the two operand values and return the result. Unset and reset cells naturally contribute zero because the grid is initialized and reset with zeros.
class Spreadsheet:
def __init__(self, rows: int):
self.grid = [[0] * 26 for i in range(rows + 1)]
def setCell(self, cell: str, value: int) -> None:
self.grid[int(cell[1:])][ord(cell[0]) - ord('A')] = value
def resetCell(self, cell: str) -> None:
self.grid[int(cell[1:])][ord(cell[0]) - ord('A')] = 0
def getValue(self, formula: str) -> int:
curr = formula[1:].split('+')
res = 0
for val in curr:
if val.isdigit():
res += int(val)
else:
res += self.grid[int(val[1:])][ord(val[0]) - ord('A')]
return resComplexity analysis
Let R be the configured row count and L the formula length. Construction time/space: O(R) because the column count is fixed 26. setCell and resetCell: O(1). getValue: O(L) time and O(L) temporary parsing space.
