- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 51 lines of Python from the credited upstream file 631.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass5class Cell:6 val: int = 07 posCount: dict[tuple[int, int], int] | None = None8 9 10class Excel:11 def __init__(self, height: int, width: str):12 self.width = ord(width) - ord('A') + 113 self.sheet = [[Cell() for _ in range(self.width)] for _ in range(height)]14 15 def set(self, row: int, column: str, val: int) -> None:16 self._getCell(row, column).val = val17 self._getCell(row, column).posCount = {}18 19 def get(self, row: int, column: str) -> int:20 cell = self._getCell(row, column)21 if not cell.posCount:22 return cell.val23 val = 024 for pos, count in cell.posCount.items():25 val += self.get(pos self.width + 1, chr(pos %26 self.width + ord('A'))) * count27 return val28 29 def sum(self, row: int, column: str, numbers: list[str]) -> int:30 self._getCell(row, column).posCount = self._parse(numbers)31 return self.get(row, column)32 33 def _getCell(self, row: int, column: str) -> Cell:34 return self.sheet[row - 1][ord(column) - ord('A')]35 36 def _parse(self, numbers: list[str]) -> dict[int, int]:37 count: dict[int, int] = {}38 for s in numbers:39 startRow, startCol, endRow, endCol = self._parseRange(s)40 for i in range(startRow - 1, endRow):41 for j in range(ord(startCol) - ord('A'), ord(endCol) - ord('A') + 1):42 pos = i * self.width + j43 count[pos] = count.get(pos, 0) + 144 return count45 46 def _parseRange(self, s: str) -> tuple[int, str, int, str]:47 if ':' not in s:48 return int(s[1:]), s[0], int(s[1:]), s[0]49 l, r = s.split(':')50 return int(l[1:]), l[0], int(r[1:]), r[0]51