Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created September 19, 2025 19:49
Show Gist options
  • Select an option

  • Save Ifihan/71b0ca10aec16c2fbba11c42bfc50bc7 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/71b0ca10aec16c2fbba11c42bfc50bc7 to your computer and use it in GitHub Desktop.
Design Spreadsheet

Question

Approach

  • Storage: I use a dictionary self.cells where 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).

Implementation

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) 

Complexities

  • Time: setCell / resetCell / getValue: O(1) average (hash map)
  • Space: Proportional to number of explicitly set cells
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment