#3484

Design Spreadsheet

Medium
ArrayHash TableStringDesignMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a hashmap allows for efficient cell access and updates, reducing the need for a full grid representation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hashmap to store cell values, where keys are cell references.
  2. 2Step 2: For setCell, directly update the hashmap with the cell reference and value.
  3. 3Step 3: For getValue, parse the formula and retrieve values from the hashmap, handling missing cells by returning 0.
solution.py10 lines
1class Spreadsheet:
2    def __init__(self, rows):
3        self.cells = {}
4    def setCell(self, cell, value):
5        self.cells[cell] = value
6    def resetCell(self, cell):
7        self.setCell(cell, 0)
8    def getValue(self, formula):
9        x, y = formula[1:].split('+')
10        return self.cells.get(x, 0) + self.cells.get(y, 0)

Complexity note: The hashmap allows for constant time access to cell values, making operations efficient.

  • 1Using a hashmap optimizes cell access.
  • 2Resetting cells is straightforward with direct updates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.