Packing a Fixed-Size Block from a Large Mempool with CPFP
Greedy & IntervalsModel answerLast updated
Design a fee-maximizing transaction selector for a size-capped block, extend it to parent/child dependencies with CPFP scoring, and derive a minimum child fee.
Context
A miner builds a candidate block from a mempool — an unordered collection of pending transactions. The block has a fixed capacity B = 100 (in the same units as transaction size), and the miner keeps every fee from every transaction it includes. Each transaction has three fields: id, fee (a non-negative integer), and size.
The mempool may be enormous, so the interviewer explicitly prefers a fast heuristic over an exact optimizer, even if the heuristic leaves a little fee on the table.
Part 1 — Fill one block
Implement mine_block(mempool) -> list[Transaction] returning the transactions to mine, whose sizes sum to at most B, maximizing total collected fee subject to the stated speed preference. State your time and space complexity.
Cover: the selection rule and why it matches a block whose scarce resource is space; what you do when the next candidate no longer fits; inputs where the rule behaves poorly; and how your cost compares to an exact method on a very large mempool.
Part 2 — Parents and Child-Pays-For-Parent
Add a parent_id field. A transaction's parent must be mined in the same block and appear earlier in the returned list; if parent_id is absent, its parent was already mined. A parent may have multiple children; a parent_id pointing at a transaction not in the mempool should be treated as already mined (confirm with the interviewer). No cycles exist.
Child-Pays-For-Parent (CPFP) means a child may overpay so the miner is rewarded for pulling in its low-fee parent — possibly a chain of ancestors. Rework mine_block so that:
- selected transactions fit in
B; - every selected transaction's parent is also selected;
- parents are listed before children.
Cover: a score that reflects the unmined ancestors a transaction drags along; how to keep scores correct once an ancestor was already pulled in by a different child; and the cost on a large mempool.
Part 3 — Optional: the minimum fee a child must pay
Implement min_fee(mempool, parent_id, child_size) -> uint64: the fee a new child of size child_size should pay so that it and its parent both land in the next block that your Part 2 mine_block would build from the mempool plus this child.
Cover: a precise definition of "minimum" tied to your selection rule; an algorithm to find it with exact integer arithmetic; and cases where every fee works (e.g., parent and child fit and the block would otherwise be empty) or none can (parent and child together exceed B, or an ancestor is missing from the mempool).
Hints
Hint 1
When space is the bottleneck and each item can be taken at most once, the natural fast heuristic is to rank candidates by fee per unit size rather than raw fee.
Hint 2
For a first fit, sort by ratio and sweep; the leftover gap at the end is where a more careful re-pick of one item could recover fee.
Hint 3
For CPFP, a transaction's effective score is the total fee of itself plus all not-yet-selected ancestors divided by the total size of that same package; recompute as the block fills.
Hint 4
For min_fee, binary search the child fee (monotone in whether the pair is selected) or solve the boundary inequality directly with integer cross-multiplication.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Ratio-greedy packing
This is 0/1 knapsack (each transaction at most once, capacity 100), which is NP-hard in general and quadratic-in-n-times-B for exact DP. With a very large mempool the interviewer wants speed, so use the classic fractional-knapsack idea as a heuristic: sort by fee per unit size descending and take while it fits.
ratio = fee / size // compare a.fee*b.size vs b.fee*a.size to avoid floats
sort mempool by ratio desc, tie-break by higher fee, then smaller size, then id (determinism)
total = 0; out = []
for tx in sorted:
if total + tx.size <= B:
out.append(tx); total += tx.size
return out
- Rule and rationale: space is the scarce resource, so fee-per-byte is the right currency. A large low-ratio transaction that fills the block early can block two smaller higher-ratio ones; raw fee ordering ignores that.
- When the next candidate doesn't fit: skip it and continue scanning — never stop at the first miss.
- Weak inputs: classic knapsack pathologies. Example:
B=100, one item of size 60 fee 100 (ratio 1.67) and two of size 50 fee 80 (ratio 1.6). Greedy takes the 60 for 100 fee and wastes 40 bytes; the optimum is two 50s for 160. Another: a single size-51, fee-100 item plus a size-50, fee-99 item — greedy takes 100, optimum is 99+… but nothing else fits, so the loss is small; adversarial mixes lose up to roughly the fractional-gap bound (bounded by one item's value). - Complexity: sort is
O(n log n)time,O(n)space for the sorted array,O(1)extra for the block. It is a single pass after sorting and never looks atBbins. Exact DP isO(n·B)time andO(B)space plus parent pointers for reconstruction — forn = 10^7andB = 100that's ~10^9 operations, too slow and, worse, the reconstruction bookkeeping is heavy. - Improvement on leftover space: after the sweep, run a small bounded exact DP restricted to the remaining candidates and the remaining capacity
B - total, capped at, say, the top 500 leftovers. That recovers most of the greedy gap at near-linear cost.
Part 2 — CPFP-aware selection
Effective score of a transaction = total fee of {it + its unselected ancestors} divided by total size of the same set. Once a set becomes "selected" (because some descendant was picked), later candidates no longer need to pay for it — their scores rise.
build children map; in_degree
selected = {}; picked = []
remaining = B
// compute a score on demand
def package(tx): // walk up until a selected ancestor or root
fee, size, unsel = 0,0,[]
node = tx
while node and node.id not in selected:
fee += node.fee; size += node.size; unsel.append(node); node = parents[node.id]
return fee/size, unsel
Use a max-heap keyed by recomputed ratio (lazy deletion: when a heap entry's stored ratio no longer matches the current package ratio, recompute and re-push). Pop the best; if its package fits in remaining, select the whole unselected chain (append parents before children — since the chain is a simple path, appending from the root of the unselected suffix works), mark them selected, subtract the package size; else try the next.
- Multiple children: one child pulling in the parent marks it selected, so a sibling's package shrinks to just itself — correct, because the parent's fee is already counted once.
- Missing parent id: treat the parent as already mined (consistent with Part 1's "no parent id" convention). Confirm this assumption aloud.
- Ordering: inserting a whole ancestor path when the descendant is picked naturally keeps parents before children; if you insert a node whose parent is later selected via another branch, guard against double counting by the
selectedset. - Complexity: each node's package is recomputed a bounded number of times as ancestors get selected; overall
O((n + k) log n)wherekis the number of invalidations (roughly the number of ancestor-selections times depth), versusO(n log n)in Part 1. Acceptable when chain depth is small; cap package depth to avoid pathological chains.
Part 3 — Minimum fee via monotone search
The minimum fee is the smallest f such that, in mine_block on mempool + child(parent, f, child_size), the child and its parent are both selected together. Call this selected(f); it is monotone non-decreasing in f (a higher fee only raises the package ratio), so binary search:
lo, hi = 0, 2^64 - 1
if not selected(hi): return NO_SOLUTION (e.g., size overflow)
while lo < hi:
mid = lo + (hi - lo)//2
if selected(mid): hi = mid
else: lo = mid + 1
return lo
Compare all ratios with integer cross-multiplication (fee_a * size_b >= fee_b * size_a) so the search is exact with no float error.
- Any fee works: if the parent's branch fits and the greedy sweep would always pick the pair (e.g., no competing candidates). Minimum is then 0.
- No fee works: parent + child sizes exceed
B, or an ancestor is missing from the mempool, or other packages strictly dominate. Return a sentinel and say so. - Cost:
O(log 2^64 · n log n)— a few dozen re-runs of Part 2; fine for a screen, and you can shrinkhito a coarse upper bound first.
Common mistakes
Optimalizing with full 0/1 knapsack DP and blowing the time budget; forgetting deterministic tie-breaks; using floats for ratios (off-by-one near-equal ratios); counting a parent's fee twice through two children; letting a child appear before its parent in the output; and in Part 3, ignoring ancestors so the returned fee under-pays the chain. Confirm edge cases out loud: transactions larger than B, missing parents, an empty mempool, and a leftover gap no remaining transaction fits.