-
Storage: I use a dictionary
self.cellswhere keys are(col, row)tuples (like("A", 1)) and values are integers. This avoids building a full grid of zeros. -
setCell: Updates the dictionary with the given value.
-
resetCell: Deletes the entry for that cell (so its value defaults to 0).
-
getValue: Parses the formula
=X+Y. Each operand is either an integer or a cell reference.- If it’s a number → convert to int.
- If it’s a cell reference → lookup in
self.cells, defaulting to 0.
-
Parsing:
_parse_cell("B12") → ("B", 12).
class Spreadsheet:
def __init__(self, rows: int):
self.rows = rows
self.cells: Dict[Tuple[str, int], int] = {}
def setCell(self, cell: str, value: int) -> None:
col, row = self._parse_cell(cell)
self.cells[(col, row)] = value
def resetCell(self, cell: str) -> None:
col, row = self._parse_cell(cell)
if (col, row) in self.cells:
del self.cells[(col, row)]
def getValue(self, formula: str) -> int:
left, right = formula[1:].split("+")
return self._get_operand_value(left) + self._get_operand_value(right)
def _parse_cell(self, cell: str) -> Tuple[str, int]:
col = cell[0]
row = int(cell[1:])
return col, row
def _get_operand_value(self, operand: str) -> int:
if operand.isdigit():
return int(operand)
else:
col, row = self._parse_cell(operand)
return self.cells.get((col, row), 0) - Time:
setCell/resetCell/getValue: O(1) average (hash map) - Space: Proportional to number of explicitly set cells