- 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
- 71 lines of Java from the credited upstream file 631.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 6 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.
1class Cell {2 public int val = 0;3 public Map<Integer, Integer> posCount = new HashMap<>(); 4 public Cell(int val, Map<Integer, Integer> posCount) {5 this.val = val;6 this.posCount = posCount;7 }8}9 10class Excel {11 public Excel(int height, char width) {12 this.width = width;13 this.sheet = new Cell[height][width];14 15 for (int i = 0; i < height; ++i)16 for (int j = 0; j < width; ++j)17 sheet[i][j] = new Cell(0, null);18 }19 20 public void set(int row, char column, int val) {21 sheet[row - 1][column - 'A'] = new Cell(val, null);22 }23 24 public int get(int row, char column) {25 Cell cell = sheet[row - 1][column - 'A'];26 if (cell.posCount == null)27 return cell.val;28 29 int val = 0;30 for (Map.Entry<Integer, Integer> entry : cell.posCount.entrySet()) {31 final int pos = entry.getKey();32 final int count = entry.getValue();33 val += get(pos / width + 1, (char) ((pos % width) + 'A')) * count;34 }35 return val;36 }37 38 public int sum(int row, char column, String[] numbers) {39 sheet[row - 1][column - 'A'].posCount = parse(numbers);40 return get(row, column);41 }42 43 private int width;44 private Cell[][] sheet;45 46 private Map<Integer, Integer> parse(String[] numbers) {47 Map<Integer, Integer> count = new HashMap<>();48 49 for (final String s : numbers) {50 Pair<String, String> tokens = parse(s);51 final int startRow = Integer.parseInt(tokens.getKey().substring(1));52 final char startCol = tokens.getKey().charAt(0);53 final int endRow = Integer.parseInt(tokens.getValue().substring(1));54 final char endCol = tokens.getValue().charAt(0);55 for (int i = startRow - 1; i < endRow; ++i)56 for (int j = startCol - 'A'; j < endCol - 'A' + 1; ++j)57 count.merge(i * width + j, 1, Integer::sum);58 }59 60 return count;61 }62 63 private Pair<String, String> parse(final String s) {64 if (!s.contains(":"))65 return new Pair<>(s, s);66 67 String[] tokens = s.split(":");68 return new Pair<>(tokens[0], tokens[1]);69 }70}71