Design Data Structures · Pattern 8 of 10
Dependency graphs: formulas that update
A formula cell depends on other cells, which may depend on more. Store each formula as the cells it adds (with counts), and compute a cell by following those edges, so a change anywhere always shows up.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Cells or values defined in terms of other cells
- Changing one value must update everything that depends on it
- The dependencies form a graph with no cycles
The template
class Excel {
int[][] val;
Map<Integer, Map<Integer, Integer>> formula = new HashMap<>(); // cell -> (cell it adds -> times)
Excel(int height, char width) { val = new int[height + 1][width - 'A' + 1]; }
int id(int row, char col) { return row * 26 + (col - 'A'); }
void set(int row, char column, int v) {
formula.remove(id(row, column)); // a plain value replaces any formula
val[row][column - 'A'] = v;
}
int get(int row, char column) {
Map<Integer, Integer> f = formula.get(id(row, column));
if (f == null) return val[row][column - 'A'];
int total = 0; // follow the edges: always up to date
for (var e : f.entrySet()) total += e.getValue() * get(e.getKey() / 26, (char) ('A' + e.getKey() % 26));
return total;
}
int sum(int row, char column, String[] numbers) {
Map<Integer, Integer> f = new HashMap<>();
for (String s : numbers) { // "B2" or "A1:C3"
String[] p = s.split(":");
String to = p[p.length - 1];
for (int r = Integer.parseInt(p[0].substring(1)); r <= Integer.parseInt(to.substring(1)); r++)
for (char c = p[0].charAt(0); c <= to.charAt(0); c++) f.merge(id(r, c), 1, Integer::sum);
}
formula.put(id(row, column), f);
return get(row, column);
}
} class Excel:
def __init__(self, height, width):
self.val = {} # (row, col) -> value
self.formula = {} # (row, col) -> {cell it adds: times}
def set(self, row, column, val):
self.formula.pop((row, column), None) # a plain value replaces any formula
self.val[(row, column)] = val
def get(self, row, column):
f = self.formula.get((row, column))
if f is None:
return self.val.get((row, column), 0)
return sum(times * self.get(r, c) for (r, c), times in f.items()) # follow the edges
def sum(self, row, column, numbers):
f = {}
for s in numbers: # "B2" or "A1:C3"
parts = s.split(":")
a, b = parts[0], parts[-1]
for r in range(int(a[1:]), int(b[1:]) + 1):
for c in range(ord(a[0]), ord(b[0]) + 1):
f[(r, chr(c))] = f.get((r, chr(c)), 0) + 1
self.formula[(row, column)] = f
return self.get(row, column) class Excel {
vector<vector<int>> val;
unordered_map<int, unordered_map<int, int>> formula; // cell -> (cell it adds -> times)
int id(int row, char col) { return row * 26 + (col - 'A'); }
public:
Excel(int height, char width) : val(height + 1, vector<int>(width - 'A' + 1)) {}
void set(int row, char column, int v) {
formula.erase(id(row, column)); // a plain value replaces any formula
val[row][column - 'A'] = v;
}
int get(int row, char column) {
auto it = formula.find(id(row, column));
if (it == formula.end()) return val[row][column - 'A'];
int total = 0; // follow the edges: always up to date
for (auto [cell, times] : it->second) total += times * get(cell / 26, 'A' + cell % 26);
return total;
}
int sum(int row, char column, vector<string> numbers) {
unordered_map<int, int> f;
for (string& s : numbers) { // "B2" or "A1:C3"
size_t k = s.find(':');
string a = s.substr(0, k), b = k == string::npos ? a : s.substr(k + 1);
for (int r = stoi(a.substr(1)); r <= stoi(b.substr(1)); r++)
for (char c = a[0]; c <= b[0]; c++) f[id(r, c)]++;
}
formula[id(row, column)] = f;
return get(row, column);
}
}; class Excel {
constructor(height, width) { this.val = new Map(); this.formula = new Map(); } // key "A1"
set(row, column, val) {
this.formula.delete(column + row); // a plain value replaces any formula
this.val.set(column + row, val);
}
get(row, column) {
const f = this.formula.get(column + row);
if (!f) return this.val.get(column + row) ?? 0;
let total = 0; // follow the edges: always up to date
for (const [cell, times] of f) total += times * this.get(Number(cell.slice(1)), cell[0]);
return total;
}
sum(row, column, numbers) {
const f = new Map();
for (const s of numbers) { // "B2" or "A1:C3"
const [a, b = a] = s.split(":");
for (let r = Number(a.slice(1)); r <= Number(b.slice(1)); r++)
for (let c = a.charCodeAt(0); c <= b.charCodeAt(0); c++) {
const cell = String.fromCharCode(c) + r;
f.set(cell, (f.get(cell) ?? 0) + 1);
}
}
this.formula.set(column + row, f);
return this.get(row, column);
}
} The variations
-
1Store edges, evaluate on read
Each formula cell keeps a map from input cell to how many times it is added. Reading a cell walks those edges down to plain values, so it is always fresh. The other trade-off keeps the reverse edges and pushes every change to the cells that depend on it, in topological order, which makes
getO(1).
Mistakes to avoid
- Storing the formula's result instead of the formula: later changes to the inputs are lost.
- Forgetting that
setmust clear a cell's formula, or a cell keeps summing its old inputs. - Treating a range like
A1:B2as two cells instead of every cell in the rectangle, or dropping a cell that appears twice.
Lesson done
Next: Concurrency: a bounded blocking queue →Mark it done once you can write the template from memory and you have solved the worked examples yourself.