Design Excel Sum Formula Problem
Description
LeetCode Problem 631.
Design the basic function of Excel and implement the function of the sum formula.
Implement the Excel class:
Excel(int height, char width)Initializes the object with theheightand thewidthof the sheet. The sheet is an integer matrixmatof sizeheight x widthwith the row index in the range[1, height]and the column index in the range['A', width]. All the values should be zero initially.void set(int row, char column, int val)Changes the value atmat[row][column]to beval.int get(int row, char column)Returns the value atmat[row][column].int sum(int row, char column, List<String> numbers)Sets the value atmat[row][column]to be the sum of cells represented bynumbersand returns the value atmat[row][column]. This sum formula should exist until this cell is overlapped by another value or another sum formula.numbers[i]could be on the format:"ColRow"that represents a single cell.- For example,
"F7"represents the cellmat[7]['F'].
- For example,
"ColRow1:ColRow2"that represents a range of cells. The range will always be a rectangle where"ColRow1"represent the position of the top-left cell, and"ColRow2"represents the position of the bottom-right cell.- For example,
"B3:F7"represents the cellsmat[i][j]for3 <= i <= 7and'B' <= j <= 'F'.
- For example,
Note: You could assume that there will not be any circular sum reference.
- For example,
mat[1]['A'] == sum(1, "B")andmat[1]['B'] == sum(1, "A").
Example 1:
Input
["Excel", "set", "sum", "set", "get"]
[[3, "C"], [1, "A", 2], [3, "C", ["A1", "A1:B2"]], [2, "B", 2], [3, "C"]]
Output
[null, null, 4, null, 6]
Explanation
Excel excel = new Excel(3, "C");
// construct a 3*3 2D array with all zero.
// A B C
// 1 0 0 0
// 2 0 0 0
// 3 0 0 0
excel.set(1, "A", 2);
// set mat[1]["A"] to be 2.
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 0
excel.sum(3, "C", ["A1", "A1:B2"]); // return 4
// set mat[3]["C"] to be the sum of value at mat[1]["A"] and the values sum of the rectangle range whose top-left cell is mat[1]["A"] and bottom-right cell is mat[2]["B"].
// A B C
// 1 2 0 0
// 2 0 0 0
// 3 0 0 4
excel.set(2, "B", 2);
// set mat[2]["B"] to be 2. Note mat[3]["C"] should also be changed.
// A B C
// 1 2 0 0
// 2 0 2 0
// 3 0 0 6
excel.get(3, "C"); // return 6
Constraints:
1 <= height <= 26'A' <= width <= 'Z'1 <= row <= height'A' <= column <= width-100 <= val <= 1001 <= numbers.length <= 5numbers[i]has the format"ColRow"or"ColRow1:ColRow2".- At most
100calls will be made toset,get, andsum.
Solution
Approach: Store Formulas, Evaluate on Read
The hard requirement is that a sum stays live: after excel.set(2, "B", 2) in the example, C3 must change from 4 to 6 even though nobody touched C3. So a formula cell cannot just store the number it had when sum was called. Instead, each cell holds one of two things:
- a plain value, kept in a
height x 26grid, or - a formula: a map from each referenced cell to how many times it is added.
The count matters because references may overlap. In the example, ["A1", "A1:B2"] adds A1 twice, so A1 gets count 2.
The operations then become:
set(row, column, val): remove any formula on the cell and storeval. A value overwrites a formula.sum(row, column, numbers): expand every entry ofnumbersinto cells (a single"F7", or every cell of the rectangle"B3:F7"), count them, store this map as the cell's formula (replacing whatever was there) and returnget(row, column).get(row, column): if the cell has no formula, return its value. Otherwise return the sum ofcount * get(ref)over its references, recursively. The problem promises no circular references, so the recursion always ends.
One subtlety: formulas can share cells (C1 and C2 both adding B1, C2 also adding C1, ...). Evaluating such a chain naively can recompute the same formula cell a huge number of times. Keeping a small memo per get call, from formula cell to its value, computes each formula at most once. The memo must be fresh for every call, because a later set can change any value.
Complexity: set is O(1). sum takes O(k) to expand its references, where k is the number of cells they cover (at most 5 * 26 * 26). get takes O(F · k) in the worst case, where F is the number of formula cells, since each formula is evaluated once. Space is O(height · 26 + total formula size).
from collections import Counter
class Excel:
def __init__(self, height: int, width: str):
self.vals = [[0] * 26 for _ in range(height + 1)]
# (row, col) -> Counter of the cells its formula adds up (a cell can be counted more than once).
self.formulas = {}
def set(self, row: int, column: str, val: int) -> None:
cell = (row, ord(column) - ord("A"))
self.formulas.pop(cell, None) # a plain value replaces a formula
self.vals[row][cell[1]] = val
def get(self, row: int, column: str) -> int:
return self._eval((row, ord(column) - ord("A")), {})
def sum(self, row: int, column: str, numbers: List[str]) -> int:
refs = Counter()
for part in numbers:
first, _, last = part.partition(":")
r1, c1 = self._parse(first)
r2, c2 = self._parse(last or first)
for r in range(r1, r2 + 1):
for c in range(c1, c2 + 1):
refs[(r, c)] += 1
self.formulas[(row, ord(column) - ord("A"))] = refs
return self.get(row, column)
def _parse(self, name):
return int(name[1:]), ord(name[0]) - ord("A")
def _eval(self, cell, memo):
if cell not in self.formulas:
return self.vals[cell[0]][cell[1]]
if cell not in memo: # memo: each formula is computed once per call
memo[cell] = sum(times * self._eval(ref, memo) for ref, times in self.formulas[cell].items())
return memo[cell]