Problem Statement in English

Your task is to design a spreadhseet with the following methods:

  • setCell(cell: str, value: int): Sets the value of the cell with the given name to the given value.
  • resetCell(cell: str): Resets the value of the cell with the given name to 0.
  • getValue(formula: str): Returns the value of the cell with the given name. The formula is a string that can be either a number or a cell name. If it is a number, return it as an integer. If it is a cell name, return the value of that cell.

Approach

This is just an implementation question.

Note that the rows variable is a scam, and it’s better not to actually allocate those many rows in the spreadhseet. Just do it in an ad-hoc manner. More efficient.


Solution in Python


class Spreadsheet:

    def __init__(self, rows: int):
        self.hm = defaultdict(int)

    def setCell(self, cell: str, value: int) -> None:
        self.hm[cell] = value

    def resetCell(self, cell: str) -> None:
        self.hm[cell] = 0

    def getValue(self, formula: str) -> int:
        formula = formula[1:]
        l = formula.split("+")

        a = int(l[0]) if l[0].isdigit() else int(self.hm[l[0]])
        b = int(l[1]) if l[1].isdigit() else int(self.hm[l[1]])

        return a+b

Complexity

  • Time: $O(1)$
    All operations are constant time.

  • Space: $O(rows)$
    Since in the worst case we store all the rows in the hashmap.


And we are done.