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).
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
// 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);
}
} # Range Sum Query - Mutable: a Fenwick tree makes update and sum both O(log n)
class NumArray:
def __init__(self, nums):
self.nums = [0] * len(nums)
self.tree = [0] * (len(nums) + 1) # 1-indexed
for i, x in enumerate(nums):
self.update(i, x)
def update(self, index, val):
delta = val - self.nums[index]
self.nums[index] = val
i = index + 1
while i < len(self.tree): # every node covering index
self.tree[i] += delta
i += i & -i
def prefix(self, i): # nums[0] + ... + nums[i - 1]
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i # drop the lowest set bit
return s
def sumRange(self, left, right):
return self.prefix(right + 1) - self.prefix(left) // Range Sum Query - Mutable: a Fenwick tree makes update and sum both O(log n)
class NumArray {
vector<int> nums, tree; // tree is 1-indexed
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;
}
public:
NumArray(vector<int>& a) : nums(a.size()), tree(a.size() + 1) {
for (int i = 0; i < (int)a.size(); i++) update(i, a[i]);
}
void update(int index, int val) {
int delta = val - nums[index];
nums[index] = val;
for (int i = index + 1; i < (int)tree.size(); i += i & -i) tree[i] += delta; // every node covering index
}
int sumRange(int left, int right) {
return prefix(right + 1) - prefix(left);
}
}; // Range Sum Query - Mutable: a Fenwick tree makes update and sum both O(log n)
class NumArray {
constructor(nums) {
this.nums = new Array(nums.length).fill(0);
this.tree = new Array(nums.length + 1).fill(0); // 1-indexed
nums.forEach((x, i) => this.update(i, x));
}
update(index, val) {
const delta = val - this.nums[index];
this.nums[index] = val;
for (let i = index + 1; i < this.tree.length; i += i & -i) this.tree[i] += delta; // every node covering index
}
prefix(i) { // nums[0] + ... + nums[i - 1]
let s = 0;
for (; i > 0; i -= i & -i) s += this.tree[i]; // drop the lowest set bit
return s;
}
sumRange(left, right) {
return this.prefix(right + 1) - this.prefix(left);
}
} The variations
-
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).
Now you solve -
2Keep counters up to date on write
Update a small summary on every write so reads are O(1). Tic-tac-toe keeps
+1/-1sums 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.Now you solve- Design A Leaderboard Medium Stuck? solution
- Simple Bank System Medium Stuck? solution
-
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 -
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.
Now you solve -
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.Now you solve -
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 & -ito 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 & -inever 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.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.