Skip to content

3484. Design Spreadsheet

  • Time:
    • Constructor: $O(1)$
    • setCell(cell: str, value: int): $O(1)$
    • resetCell(cell: str): $O(1)$
    • getValue(formulat: str): $O(1)$
  • Space: $O(|\texttt{setCell(cell: str, value: int)}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Spreadsheet {
 public:
  Spreadsheet(int rows) {}

  void setCell(string cell, int value) {
    spreadsheet[cell] = value;
  }

  void resetCell(string cell) {
    spreadsheet[cell] = 0;
  }

  int getValue(string formula) {
    const int i = formula.find('+');
    return getToken(formula.substr(1, i - 1)) + getToken(formula.substr(i + 1));
  }

 private:
  unordered_map<string, int> spreadsheet;

  int getToken(const string& token) {
    return isdigit(token[0])
               ? stoi(token)
               : (spreadsheet.contains(token) ? spreadsheet[token] : 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Spreadsheet {
  public Spreadsheet(int rows) {}

  public void setCell(String cell, int value) {
    spreadsheet.put(cell, value);
  }

  public void resetCell(String cell) {
    spreadsheet.put(cell, 0);
  }

  public int getValue(String formula) {
    final int i = formula.indexOf('+');
    return getToken(formula.substring(1, i)) + getToken(formula.substring(i + 1));
  }

  private Map<String, Integer> spreadsheet = new HashMap<>();

  private int getToken(final String token) {
    return Character.isDigit(token.charAt(0)) ? Integer.parseInt(token)
                                              : spreadsheet.getOrDefault(token, 0);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Spreadsheet:
  def __init__(self, rows: int) -> None:
    self.spreadsheet = {}

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

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

  def getValue(self, formula: str) -> int:
    i = formula.find('+')
    return self._getToken(formula[1:i]) + self._getToken(formula[i+1:])

  def _getToken(self, token: str) -> int:
    return int(token) if token[0].isdigit() else self.spreadsheet.get(token, 0)