- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 60 lines of C++ from the credited upstream file 631.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Cell {2 int val = 0;3 unordered_map<int, int> posCount; 4};5 6class Excel {7 public:8 Excel(int height, char width)9 : width(width), sheet(height, vector<Cell>(width)) {}10 11 void set(int row, char column, int val) {12 getCell(row, column) = {val, {}};13 }14 15 int get(int row, char column) {16 const Cell& cell = getCell(row, column);17 if (cell.posCount.empty())18 return cell.val;19 20 int val = 0;21 for (const auto& [pos, count] : cell.posCount)22 val += get(pos / width + 1, pos % width + 'A') * count;23 return val;24 }25 26 int sum(int row, char column, vector<string> numbers) {27 getCell(row, column).posCount = parse(numbers);28 return get(row, column);29 }30 31 private:32 int width;33 vector<vector<Cell>> sheet;34 35 Cell& getCell(int row, char column) {36 return sheet[row - 1][column - 'A'];37 }38 39 unordered_map<int, int> parse(const vector<string>& numbers) {40 unordered_map<int, int> count;41 for (const string& s : numbers) {42 const auto [startRow, startCol, endRow, endCol] = parse(s);43 for (int i = startRow - 1; i < endRow; ++i)44 for (int j = startCol - 'A'; j < endCol - 'A' + 1; ++j)45 ++count[i * width + j];46 }47 return count;48 }49 50 tuple<int, char, int, char> parse(const string& s) {51 if (s.find(':') == string::npos)52 return {stoi(s.substr(1)), s[0], stoi(s.substr(1)), s[0]};53 54 const int colonIndex = s.find_first_of(':');55 const string& l = s.substr(0, colonIndex);56 const string& r = s.substr(colonIndex + 1);57 return {stoi(l.substr(1)), l[0], stoi(r.substr(1)), r[0]};58 }59};60