Design Data Structures · Pattern 1 of 10

Pre-processing and trade-offs: pay on write or on read

Decide which method should be fast, and do the work in the other one. Index the data when the class is built, keep counters up to date on every write, or use a tree that makes both sides O(log n).

6 variations · 14 problems · 3 with animated walkthroughs

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

  • The same query is asked many times on data that rarely changes
  • Writes and reads are both frequent and each must be fast
  • You need your own hash table, iterator or index
  • Counting wins in a game by row, column or player

The template

Pre-processing + tradeoffs
// Range Sum Query - Mutable: a Fenwick tree makes update and sum both O(log n)
class NumArray {
    int[] nums, tree;                                 // tree is 1-indexed
    NumArray(int[] nums) {
        this.nums = new int[nums.length];
        tree = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) update(i, nums[i]);
    }
    void update(int index, int val) {
        int delta = val - nums[index];
        nums[index] = val;
        for (int i = index + 1; i < tree.length; i += i & -i) tree[i] += delta;   // every node covering index
    }
    int prefix(int i) {                               // nums[0] + ... + nums[i - 1]
        int s = 0;
        for (; i > 0; i -= i & -i) s += tree[i];      // drop the lowest set bit
        return s;
    }
    int sumRange(int left, int right) {
        return prefix(right + 1) - prefix(left);
    }
}

The variations

  1. 1Index the data up front

    If queries repeat, do the lookup work once. Store where each value lives, or the positions of each word in a sorted list, so every call is a map lookup (plus a two-pointer walk for word distances).

  2. 2Keep counters up to date on write

    Update a small summary on every write so reads are O(1). Tic-tac-toe keeps +1 / -1 sums per row, column and diagonal; a win is a sum of ±n. A leaderboard keeps a score per player; a bank keeps balances in an array and checks bounds first.

  3. 3Build your own hash table

    An array of buckets, picked by key % size, each holding a small list of entries. Collisions go in the same bucket. With small keys, a plain boolean or int array is a valid trade-off too.

    Now you solve
  4. 4Keys with structure: paths and timestamps

    Turn the key into something a map can use. A file path is a map from the full path string to a value, but its parent must exist first. Timestamps with a fixed format compare correctly as strings, so cut them to the asked granularity and compare prefixes.

  5. 5Iterators and sparse data

    Store only what matters. An iterator keeps two indexes (row and column) and skips empty rows in hasNext. A sparse vector keeps only its non-zero (index, value) pairs, and a dot product walks two such lists with two pointers.

  6. 6Both fast: a tree over prefix sums

    A prefix sum array makes queries O(1) but updates O(n); a plain array is the opposite. A Fenwick tree (or segment tree) meets in the middle: both are O(log n), using i & -i to jump between nodes.

Mistakes to avoid

  • Recomputing from scratch on every query when the data could be indexed once in the constructor.
  • Fenwick tree: using index 0 (the loop i -= i & -i never moves past 0). Shift every index by one.
  • Tic-tac-toe: scanning the board after every move instead of keeping counts per row, column and diagonal.
Next: Linked list designs: LRU cache and friends →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.