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.

1 variation · 1 problem

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

Dependency Graph
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);
    }
}

The variations

  1. 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 get O(1).

Mistakes to avoid

  • Storing the formula's result instead of the formula: later changes to the inputs are lost.
  • Forgetting that set must clear a cell's formula, or a cell keeps summing its old inputs.
  • Treating a range like A1:B2 as two cells instead of every cell in the rectangle, or dropping a cell that appears twice.
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.