Greedy Block Assembly with Ancestor Fee Packages
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Given a pool of unconfirmed transactions waiting to enter a blockchain block of maximum size capacity (default 100), assemble a valid high-fee block rapidly even when the pool holds tens of thousands of unsorted entries.
Implement:
def select_transactions(txs: List[Dict], capacity: int = 100) -> List[str]:
Each element of txs is a dictionary with the following fields:
"id"(str): unique identifier of the transaction."fee"(intorfloat,>= 0): fee earned by the miner if this transaction is included."size"(int,>= 1): block capacity consumed by this transaction."parent_id"(optionalstrorNone): when present, non-None, and equal to the"id"of another entry intxs, that entry is an unconfirmed parent that must also be included in the block and appear before this child in the returned list. When"parent_id"is omitted,None, or absent fromtxs, the parent was already confirmed in an earlier block and imposes no size or ordering requirement.
Parent links can form multi-level chains and multiple children may depend on the same parent, with no cycles (a forest). Because low-fee ancestors can be subsidized by lucrative descendants (child-pays-for-parent, or CPFP) and throughput on large inputs matters more than exact subset-sum optimality, select transactions greedily by ancestor-package fee rate:
- At any moment, an unselected transaction
x's ancestor package consists ofxplus all of its unconfirmed ancestors not yet selected into the block. Its score is(total fee of that package) / (total size of that package), breaking ties in favor of smaller input index intxs. - Repeatedly pop the highest-scoring unselected candidate:
- If its current package size exceeds the remaining block capacity, skip it and continue scanning remaining candidates (do not terminate early, since smaller packages later may still fit).
- Otherwise, add every transaction in its missing ancestor package to the block, reduce remaining capacity accordingly, and subtract those newly added ancestors' fees and sizes from all remaining unselected descendants so shared ancestors are never charged twice.
- Return the selected transaction
"id"strings in valid parent-before-child order: scantxsin input order, and whenever a selected transaction has unemitted ancestors, emit those ancestors oldest-first immediately ahead of it.
Examples
Example 1
- Input:
txs = [{"id": "tx_a", "fee": 28, "size": 40}, {"id": "tx_b", "fee": 45, "size": 75}, {"id": "tx_c", "fee": 36, "size": 30}, {"id": "tx_d", "fee": 90, "size": 110}, {"id": "tx_e", "fee": 12, "size": 25}]capacity = 100
- Output:
["tx_a", "tx_c", "tx_e"] - Explanation: Individual fee rates are
"tx_c"(1.20),"tx_d"(0.82),"tx_a"(0.70),"tx_b"(0.60), and"tx_e"(0.48)."tx_c"enters first (70capacity left);"tx_d"exceeds100and is skipped;"tx_a"enters next (30capacity left);"tx_b"needs75 > 30and is skipped;"tx_e"fits in25 <= 30and enters. Emitting the chosen IDs in input order gives["tx_a", "tx_c", "tx_e"](total size95, total fee76).
Example 2
- Input:
txs = [{"id": "child_1", "fee": 44, "size": 15, "parent_id": "root_p"}, {"id": "solo", "fee": 35, "size": 50, "parent_id": None}, {"id": "root_p", "fee": 2, "size": 25, "parent_id": None}, {"id": "child_2", "fee": 18, "size": 20, "parent_id": "root_p"}]capacity = 80
- Output:
["root_p", "child_1", "child_2"] - Explanation: Initially
"root_p"alone scores2 / 25 = 0.08,"solo"scores35 / 50 = 0.70,"child_2"with"root_p"scores20 / 45 = 0.44, and"child_1"with"root_p"leads at(2 + 44) / (25 + 15) = 1.15. Selecting["root_p", "child_1"]uses40space (40left) and removes"root_p"from sibling"child_2"'s package, raising"child_2"to18 / 20 = 0.90ahead of"solo"(0.70, which also exceeds the remaining40space). Because"child_1"appears at index0intxs, its required parent"root_p"is emitted right before it, yielding["root_p", "child_1", "child_2"].
Constraints
0 <= len(txs) <= 100,0000 <= capacity <= 10,000(default100)- All
"id"strings intxsare unique;"fee" >= 0and"size" >= 1 - Every transaction has at most one
"parent_id", and parent dependencies form an acyclic forest
Step-by-step walkthrough
Understand the block rules, CPFP, and assumptions
A mempool is a waiting room of unconfirmed transactions competing to enter the next block of capacity
100(orcapacity). Each transaction dict hasid,fee,size, and (from Part 2 onward) an optionalparent_id. We must return a list of chosen transaction IDs such that:- Their combined
sizeis at mostcapacity. - Whenever a transaction is chosen, every unmined ancestor it depends on is also chosen and appears earlier in the output list.
- Total collected
feeis high, while running fast on a large unsorted mempool (a fast greedy heuristic is explicitly preferred over a slow exact search).
State clear assumptions for the open details in the prompt:
sizeis a positive integer (>= 1) andfeeis a non-negative number (>= 0). Any transaction or chain with size> capacityis simply skipped.- A missing
parent_id,None, or aparent_idnot present intxsmeans that parent was already mined in an earlier block and adds no constraint. - Multiple children may share one parent, and dependencies form an acyclic forest (each transaction has at most one
parent_id). - Output order follows Example 1 (
['tx_a', 'tx_c', 'tx_e']): preserve input order among chosen transactions, pulling unemitted ancestors immediately in front of a child whenever the child appeared earlier intxs.
- Their combined
Part 1: rank by fee rate and keep scanning past misfits
Block space is the scarce bottleneck. Comparing raw fees is misleading: a transaction paying
45for75units earns only0.60per unit, whereas two smaller ones paying36(size 30, rate1.20) and28(size 40, rate0.70) earn64in just70units!So in Part 1 (no parents), rank transactions by fee rate
fee / sizefrom highest to lowest. When the next candidate is larger thanremaining_room, skip it and keep scanning rather than stopping — a smaller transaction further down can still fill the leftover space.Example 1 (capacity = 100): Sorted by fee/size: tx_c: 36/30 = 1.20 -> fits! take tx_c (remaining_room = 70) tx_d: 90/110 = 0.82 -> skipped (110 > 70, larger than block anyway) tx_a: 28/40 = 0.70 -> fits! take tx_a (remaining_room = 30) tx_b: 45/75 = 0.60 -> skipped (75 > 30, keep scanning!) tx_e: 12/25 = 0.48 -> fits! take tx_e (remaining_room = 5) Chosen in input order: ['tx_a', 'tx_c', 'tx_e'] (total fee = 76)How far from optimal can greedy fee-rate get without parents? In the worst case, a tiny high-rate item
(fee=2, size=1)blocks a full-block item(fee=100, size=100). In general, greedy collects at leastOPT - max_single_fee, because right before the first skipped itemX, greedy holds the exact prefix that fractional knapsack would pick, sogreedy_so_far + fee(X) >= OPT. When individual transactions are small relative to the block, that gap is tiny.Part 2: score ancestor packages and update descendants
With parent dependencies, you cannot legally pick a child
cwithout also picking its unmined parentp(andp's unmined parentg, and so on). Child-pays-for-parent (CPFP) happens whenphas a tiny fee on its own, yet[p, c]together pay a strong combined fee per unit of combined size.Therefore, we score every candidate
xby its ancestor package —xplus all of its ancestors not yet in the block:package_rate(x) = (fee[x] + sum of missing ancestors' fees) / (size[x] + sum of missing ancestors' sizes)Crucially, once a package enters the block, any other descendant of those newly added ancestors no longer has to pay their size cost! Look at a shared parent
P(fee 0, size 40) with two childrenA(fee 50, size 10) andB(fee 30, size 10):Initially: P (fee=0, size=40) pkg(P) = 0 / 40 = 0.00 / \ A B pkg(A) = (0+50)/(40+10) = 1.00 (50,10) (30,10) pkg(B) = (0+30)/(40+10) = 0.60 After picking A's package [P, A] (uses 50 space): P is now IN the block! B no longer needs to carry P -> pkg(B) becomes 30 / 10 = 3.00!Compute initial ancestor packages in O(n) without recursion
Walking all the way up to the root independently for every transaction would take
O(n^2)time on a long chain, and recursive functions hit Python's recursion limit (~1,000) on deep chains.Instead, for each node
start, walk upparentpointers only until hitting-1or an ancestor whose package was already computed (computed[curr] == True). Then walk that short path in reverse (oldest ancestor down tostart), adding each parent's already-known package totals to its child. Every transaction is computed once inO(n)total time.from typing import List, Tuple def _initial_packages( fee: List[int], size: List[int], parent: List[int] ) -> Tuple[List[int], List[int]]: """Compute (pkg_fee, pkg_size) for each tx plus all of its unmined ancestors in O(n).""" n = len(fee) pkg_fee = [0] * n pkg_size = [0] * n computed = [False] * n for start in range(n): # Walk up the parent pointers only until we hit root (-1) or an already-computed node. path: List[int] = [] curr = start while curr != -1 and not computed[curr]: path.append(curr) curr = parent[curr] # Fill sums top-down (oldest ancestor first) so each parent's package is ready for its child. for node in reversed(path): pkg_fee[node] = fee[node] pkg_size[node] = size[node] anc = parent[node] if anc != -1: pkg_fee[node] += pkg_fee[anc] pkg_size[node] += pkg_size[anc] computed[node] = True return pkg_fee, pkg_size def _unmined_chain(i: int, parent: List[int], in_block: List[bool]) -> List[int]: """Return tx i and its ancestors not yet in the block, ordered oldest ancestor first.""" chain: List[int] = [] curr = i while curr != -1 and not in_block[curr]: chain.append(curr) curr = parent[curr] chain.reverse() return chain def _descendants(start: int, children: List[List[int]]) -> List[int]: """Collect every descendant of `start` iteratively to avoid recursion-depth limits.""" result: List[int] = [] stack = list(children[start]) while stack: node = stack.pop() result.append(node) stack.extend(children[node]) return resultSelect packages with a lazy max-heap
Python's
heapqis a min-heap and does not support modifying priorities in place. We use lazy invalidation with aversionarray:- Push
(-rate, i, version[i]). Negatingratepops the highest fee rate first, andibreaks ties in favor of earlier input positions. - When
i's package fits inremaining_room, mark every transactionancin_unmined_chain(i, ...)asin_block[anc] = True. - For every unchosen descendant
descof each newly addedanc, subtractfee[anc]andsize[anc]fromdesc's package. Then incrementversion[desc]and push a fresh heap tuple(-new_rate, desc, version[desc]). - Whenever an old heap tuple pops with
pushed_ver != version[i](orin_block[i]), skip it immediately!
from typing import Dict, List, Set, Tuple import heapq def select_transactions(txs: List[Dict], capacity: int = 100) -> List[str]: n = len(txs) if n == 0 or capacity <= 0: return [] # index_of: {tx_id_str: position_in_txs} index_of: Dict[str, int] = {} for i in range(n): index_of[txs[i]["id"]] = i fee: List[int] = [] size: List[int] = [] # parent[i] holds the index of i's unmined parent in `txs`, or -1 if already mined / absent. parent: List[int] = [] # children[p] lists indices of direct children spending from transaction p. children: List[List[int]] = [[] for _ in range(n)] for i in range(n): fee.append(txs[i]["fee"]) size.append(txs[i]["size"]) parent_id = txs[i].get("parent_id") if parent_id is not None and parent_id in index_of: p_idx = index_of[parent_id] parent.append(p_idx) children[p_idx].append(i) else: parent.append(-1) pkg_fee, pkg_size = _initial_packages(fee, size, parent) # heap stores (-package_fee_rate, tx_index, version_when_pushed): # - negating the rate turns Python's min-heap into a max-heap on fee/size; # - `tx_index` breaks ties in favor of transactions appearing earlier in `txs`; # - `version[i]` increments whenever i's package shrinks so stale heap entries are skipped. version = [0] * n heap: List[Tuple[float, int, int]] = [] for i in range(n): rate = pkg_fee[i] / pkg_size[i] heap.append((-rate, i, 0)) heapq.heapify(heap) in_block = [False] * n remaining_room = capacity while heap and remaining_room > 0: neg_rate, i, pushed_ver = heapq.heappop(heap) # Skip transactions already included or heap snapshots superseded by a newer package update. if in_block[i] or pushed_ver != version[i]: continue # If this package does not fit in the leftover space, skip it and keep checking smaller ones. if pkg_size[i] > remaining_room: continue added_chain = _unmined_chain(i, parent, in_block) for anc in added_chain: in_block[anc] = True remaining_room -= pkg_size[i] # Once `anc` is in the block, unchosen descendants no longer have to carry `anc`'s fee or size. changed: Set[int] = set() for anc in added_chain: for desc in _descendants(anc, children): if not in_block[desc]: pkg_fee[desc] -= fee[anc] pkg_size[desc] -= size[anc] changed.add(desc) for desc in changed: version[desc] += 1 new_rate = pkg_fee[desc] / pkg_size[desc] heapq.heappush(heap, (-new_rate, desc, version[desc])) return [txs[i]["id"] for i in _block_order(in_block, parent)]- Push
Emit chosen transactions with every parent before its child
Appending packages in the order the heap popped them would return
['tx_c', 'tx_a', 'tx_e']on Example 1 instead of['tx_a', 'tx_c', 'tx_e']. Conversely, simply filteringtxsin raw input order would fail whenever a child appeared before its parent intxs!_block_ordercombines both requirements cleanly: scanifrom0ton - 1. Wheneveriwas chosen and not yet emitted, walk upi's ancestor chain to collect any not-yet-emitted ancestors (which are guaranteed to be chosen too!), and emit that chain oldest-first.def _block_order(in_block: List[bool], parent: List[int]) -> List[int]: """Emit chosen tx indices in input order, pulling unemitted chosen ancestors ahead of children.""" order: List[int] = [] emitted = [False] * len(in_block) for i in range(len(in_block)): if in_block[i] and not emitted[i]: # Walk up any chosen ancestors not yet emitted so every parent precedes its child. chain: List[int] = [] curr = i while curr != -1 and not emitted[curr]: chain.append(curr) curr = parent[curr] for anc in reversed(chain): emitted[anc] = True order.append(anc) return orderTrace Example 2 (CPFP and shared-parent rescoring)
Example 2 trace (capacity = 80): 0: child_1(fee=44, size=15, parent=root_p) initial pkg = (2+44)/(25+15) = 46/40 = 1.15 1: solo (fee=35, size=50, parent=None) initial pkg = 35/50 = 0.70 2: root_p (fee=2, size=25, parent=None) initial pkg = 2/25 = 0.08 3: child_2(fee=18, size=20, parent=root_p) initial pkg = (2+18)/(25+20) = 20/45 = 0.44 1. Initial heap: child_1(-1.15, v0), solo(-0.70, v0), child_2(-0.44, v0), root_p(-0.08, v0) 2. Pop child_1(v0): chain [root_p, child_1] has size 40 <= 80 -> add root_p, child_1; room = 40 Update unchosen descendant child_2: pkg_fee=18, pkg_size=20, version=1 -> push child_2(-0.90, v1) 3. Pop child_2(v1): package [child_2] has size 20 <= 40 -> add child_2; room = 20 4. Pop solo(v0): size 50 > 20 -> skip! 5. Pop child_2(v0): stale version (0 != 1) -> skip! Pop root_p(v0): already in_block -> skip! 6. _block_order: i=0 (child_1) pulls unemitted root_p ahead -> ['root_p', 'child_1', 'child_2']If an interviewer also asks how to compute the minimum integer fee for a brand-new child
Xof sizesunder parentPso bothPandXenter the next block: first check whetherpkg_size[P] + s > capacity(impossible at any fee). Otherwise, becauseXhas no children of its own, raisingX's fee monotonically improvesX's package rate without hurting it, so you can test fee0first and otherwise binary-searchfin[0, total_mempool_fee * (pkg_size[P] + s) + 1]inO(log F)calls toselect_transactions.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def _initial_packages( fee: List[int], size: List[int], parent: List[int] ) -> Tuple[List[int], List[int]]: """Compute (pkg_fee, pkg_size) for each tx plus all of its unmined ancestors in O(n).""" n = len(fee) pkg_fee = [0] * n pkg_size = [0] * n computed = [False] * n for start in range(n): # Walk up the parent pointers only until we hit root (-1) or an already-computed node. path: List[int] = [] curr = start while curr != -1 and not computed[curr]: path.append(curr) curr = parent[curr] # Fill sums top-down (oldest ancestor first) so each parent's package is ready for its child. for node in reversed(path): pkg_fee[node] = fee[node] pkg_size[node] = size[node] anc = parent[node] if anc != -1: pkg_fee[node] += pkg_fee[anc] pkg_size[node] += pkg_size[anc] computed[node] = True return pkg_fee, pkg_size def _unmined_chain(i: int, parent: List[int], in_block: List[bool]) -> List[int]: """Return tx i and its ancestors not yet in the block, ordered oldest ancestor first.""" chain: List[int] = [] curr = i while curr != -1 and not in_block[curr]: chain.append(curr) curr = parent[curr] chain.reverse() return chain def _descendants(start: int, children: List[List[int]]) -> List[int]: """Collect every descendant of `start` iteratively to avoid recursion-depth limits.""" result: List[int] = [] stack = list(children[start]) while stack: node = stack.pop() result.append(node) stack.extend(children[node]) return result def _block_order(in_block: List[bool], parent: List[int]) -> List[int]: """Emit chosen tx indices in input order, pulling unemitted chosen ancestors ahead of children.""" order: List[int] = [] emitted = [False] * len(in_block) for i in range(len(in_block)): if in_block[i] and not emitted[i]: # Walk up any chosen ancestors not yet emitted so every parent precedes its child. chain: List[int] = [] curr = i while curr != -1 and not emitted[curr]: chain.append(curr) curr = parent[curr] for anc in reversed(chain): emitted[anc] = True order.append(anc) return order def select_transactions(txs: List[Dict], capacity: int = 100) -> List[str]: n = len(txs) if n == 0 or capacity <= 0: return [] # index_of: {tx_id_str: position_in_txs} index_of: Dict[str, int] = {} for i in range(n): index_of[txs[i]["id"]] = i fee: List[int] = [] size: List[int] = [] # parent[i] holds the index of i's unmined parent in `txs`, or -1 if already mined / absent. parent: List[int] = [] # children[p] lists indices of direct children spending from transaction p. children: List[List[int]] = [[] for _ in range(n)] for i in range(n): fee.append(txs[i]["fee"]) size.append(txs[i]["size"]) parent_id = txs[i].get("parent_id") if parent_id is not None and parent_id in index_of: p_idx = index_of[parent_id] parent.append(p_idx) children[p_idx].append(i) else: parent.append(-1) pkg_fee, pkg_size = _initial_packages(fee, size, parent) # heap stores (-package_fee_rate, tx_index, version_when_pushed): # - negating the rate turns Python's min-heap into a max-heap on fee/size; # - `tx_index` breaks ties in favor of transactions appearing earlier in `txs`; # - `version[i]` increments whenever i's package shrinks so stale heap entries are skipped. version = [0] * n heap: List[Tuple[float, int, int]] = [] for i in range(n): rate = pkg_fee[i] / pkg_size[i] heap.append((-rate, i, 0)) heapq.heapify(heap) in_block = [False] * n remaining_room = capacity while heap and remaining_room > 0: neg_rate, i, pushed_ver = heapq.heappop(heap) # Skip transactions already included or heap snapshots superseded by a newer package update. if in_block[i] or pushed_ver != version[i]: continue # If this package does not fit in the leftover space, skip it and keep checking smaller ones. if pkg_size[i] > remaining_room: continue added_chain = _unmined_chain(i, parent, in_block) for anc in added_chain: in_block[anc] = True remaining_room -= pkg_size[i] # Once `anc` is in the block, unchosen descendants no longer have to carry `anc`'s fee or size. changed: Set[int] = set() for anc in added_chain: for desc in _descendants(anc, children): if not in_block[desc]: pkg_fee[desc] -= fee[anc] pkg_size[desc] -= size[anc] changed.add(desc) for desc in changed: version[desc] += 1 new_rate = pkg_fee[desc] / pkg_size[desc] heapq.heappush(heap, (-new_rate, desc, version[desc])) return [txs[i]["id"] for i in _block_order(in_block, parent)]✅ Submit now — all tests should pass.
Intuition & how it works
Picture loading a 100-liter courier van from a giant warehouse of parcels (mempool, the pool of unconfirmed transactions waiting to be placed in a block), where each parcel takes up some liters (size) and pays a delivery tip (fee). Because space is limited, the smartest fast rule is to rank parcels by fee rate (fee / size, the tip earned per unit of space) rather than raw fee, skipping any parcel too big for the remaining space so smaller parcels behind it can still squeeze in. When parcels have dependencies, CPFP (child-pays-for-parent, a blockchain mechanism where a high-fee child transaction pays enough to make its low-fee unmined parent worth mining too) means a child cannot board the van without all of its unmined ancestors — so we score every candidate as an ancestor package (the transaction plus all of its ancestors not yet in the block), and as soon as an ancestor is loaded, we subtract its fee and size from every remaining descendant so no sibling pays for the same parent twice!
Naive approaches fail in two directions. Exhaustively checking subsets takes O(2^n) time, while recomputing every remaining transaction's ancestor chain from scratch on each pick takes O(n * depth) per round. On the other hand, ranking transactions by their individual fee / size ignores dependencies: either children get picked illegally without their parents, or low-fee parents sit at the bottom of the list forever so lucrative children waiting on them never get unlocked.
We combine O(n) top-down package initialization with a max-heap (a priority queue that always pops the highest-scoring item in O(log n) time, built by negating scores in Python's min-heap) and lazy invalidation (incrementing a version[i] counter whenever transaction i's package changes and ignoring older heap entries when they pop). Walk through capacity 100 with parent P(fee=0, size=40), children A(fee=50, size=10, parent=P) and B(fee=30, size=10, parent=P), and standalone Z(fee=28, size=45):
- Initial packages:
Pscores0 / 40 = 0.00,Ascores(0 + 50) / (40 + 10) = 1.00,Zscores28 / 45 = 0.62, andBscores(0 + 30) / (40 + 10) = 0.60. - Pop
A(rate1.00): Its missing chain[P, A]has size50 <= 100, leaving50room. NowPis in the block, soBdropsP's0fee and40size:B's package becomes30 / 10 = 3.00(version[B] = 1) and is pushed onto the heap. - Pop
B(rate3.00,v1): Size10 <= 50fits, leaving40room. - Finish:
Z(size 45 > 40) does not fit and is skipped; staleB(v0) and already-includedPare skipped. Outputting in topological order (every parent listed before its children while respecting input order otherwise) returns['P', 'A', 'B']for total fee80.
Complexity
Let n be the number of transactions in txs, A be the number of transactions ultimately included in the block (A <= capacity since every transaction has size >= 1), and U be the total number of descendant package updates triggered across those A inclusions.
- Time:
O(n + (n + U) log n). Buildingindex_of,parent, andchildrenscans thentransactions once (O(n))._initial_packagesvisits each transaction once via memoized parent walks (O(n)), andheapq.heapifybuilds the initial heap inO(n). The selection loop pushesninitial entries plusUupdated entries, and each push or pop on a heap of size at mostn + UtakesO(log(n + U)) = O(log n)time. Finally,_block_ordervisits each transaction at most once (O(n)). When there are no parents (U = 0), this simplifies toO(n log n); in real mempools unconfirmed ancestor/descendant chains are capped at small constants (for example 25 in Bitcoin Core), keepingUtiny (O(A * max_descendants)), whereas a single pathological chain of lengthnhas worst-caseU <= A * n. - Space:
O(n + U). The arraysfee,size,parent,children,pkg_fee,pkg_size,version, andin_blockeach holdO(n)items, and the heap holds at mostn + Utuples including stale versions awaiting lazy discard.
Edge cases
- Empty mempool or
capacity <= 0: Returns[]immediately without touching the heap. - Single transaction or chain larger than
capacity:pkg_size[i] > remaining_roomskips the oversized package without halting the loop; notably, if[parent, child]exceedscapacity(60 + 50 = 110 > 100),parentalone (size 60) can still be picked later on its own! - Candidate does not fit in leftover room: Skipping it lets smaller lower-rate transactions fill the remaining gap instead of wasting block space.
parent_idmissing,None, or absent fromtxs: Treated as an already-mined parent (parent[i] = -1), imposing zero size overhead or ordering constraint.- Child appears before its parent in
txs:_block_orderwalks upward from the child and emits all unemitted chosen ancestors first, guaranteeing parent-before-child validity. - Zero-fee transactions: Score
0.0on their own (entering at the very end only if leftover space remains), yet can be pulled in early if a high-fee child lifts their combined package rate. - Deep dependency chains (
> 1,000levels): Every upward and downward traversal (_initial_packages,_unmined_chain,_descendants,_block_order) uses explicit loops/stacks so Python never raisesRecursionError.
Common mistakes
- Breaking out of the loop at the first transaction that exceeds
remaining_room: In Example 1, after"tx_c"and"tx_a"consume70units, stopping when"tx_b"(size 75 > 30) pops would miss"tx_e"(size 25 <= 30) right behind it. - Scoring children by individual
fee / sizeinstead of ancestor-package rate: Either produces an invalid block (missing unmined parents), fails CPFP (never mines a0-fee parent), or lets a tiny high-fee child (fee 20, size 10) drag in a massive0-fee parent (size 90) for a poor0.20combined rate. - Forgetting to rescore siblings when a shared parent enters the block: Leaving
P's size inside siblingB's package makesBlook artificially weak (0.60instead of3.00). - Sorting chosen IDs strictly by input index at the end: Fails whenever
txslists a child at index0and its parent at index3. - Recomputing ancestor sums up to the root from scratch for every transaction: Turns
O(n)initialization intoO(n^2)on long chains.
Alternative approaches
- Exact 0/1 knapsack dynamic programming (Part 1 without parents): A 0/1 knapsack problem picks a subset of items of integer weights within
capacityto maximize value. Keeping an arraydp[c]for the best fee using at mostcsize units updates inO(n * capacity) = O(100 * n)time — linear innbecausecapacity = 100is tiny, though it requires extra backtracking tables and adapts less simply to general DAG dependencies than package-feerate greedy. - Sort once without a heap (Part 1 only): When no transaction has an unmined parent, scores never change, so sorting once by
(-fee / size, i)and scanning linearly runs inO(n log n)time andO(n)space.
Follow-up questions
- Suppose a low-fee parent has multiple children whose individual fees are too modest to justify the parent alone, yet together their combined fees would. Does ancestor-only scoring pick them, and how would you extend it to handle shared-parent families? Our ancestor-only package rule scores
[P, child_1]and[P, child_2]separately, so ifPhas fee0, size 40and two children each havefee 20, size 10, each single-child package scores20 / 50 = 0.40and loses to0.50competitors even though[P, child_1, child_2]together score40 / 60 = 0.67! To capture multi-child CPFP on trees, also generate a family candidate for each parentPby sortingP's children in descending order of individual fee rate and greedily absorbing children as long as a child's rate exceeds the running combined rateF / S(since(F + f) / (S + s) > F / Sif and only iff / s > F / S). More generally, finding the maximum-feerate ancestor-closed subset in a connected cluster reduces to parametric max-flow / closure, though tree-level child merging handles common shared-parent payouts cheaply. - If transactions stream into the mempool continuously across many blocks, how would you maintain package scores incrementally rather than recomputing from scratch each block? Keep
index_of,parent,children,pkg_fee, andpkg_sizepersistently across blocks, paired with a balanced sorted set (or indexed priority queue) keyed by(-pkg_rate, id). When a new transactionXarrives, its initial package is simply(fee[X], size[X])plus its parent's current package inO(1)time, inserted into the sorted set inO(log n). When a block is mined, permanently remove the mined transactions and subtract their fees and sizes from their remaining descendants (O(log n)per updated descendant); while assembling a candidate block template, track temporary score deltas in a scratch dictionary so the live mempool state stays untouched until a block is actually finalized. - If you needed the exact maximum possible fee for capacity 100 instead of a greedy approximation, how would you solve it both without dependencies and on parent trees, and what is the runtime? Without parents, standard 0/1 knapsack DP computes
dp[c]forc = 0..100inO(n * capacity) = O(100 * n)time. With single-parent dependencies (a forest), flatten the forest in DFS preorder so every nodek's subtree occupies a contiguous slice[k .. end[k] - 1], and definedp[k][c]as the maximum fee achievable from indexkonward withccapacity left: if we skip nodek, we must skip its entire subtree (dp[end[k]][c]), and if we take nodek, we unlock its children (fee[k] + dp[k + 1][c - size[k]]), which still runs in exactO(n * capacity)time! Note that if transactions could spend from multiple unmined parents (a general DAG rather than a forest), exact selection becomes NP-hard even for moderate capacities. - How would you validate both theoretically and empirically that this greedy heuristic performs close to optimal on real workloads? Start with automated property tests verifying hard invariants on every output: total size
<= capacity, every unmined ancestor included, and every parent appearing before its children. Next, combine theoretical and empirical quality bounds: theoretically, without parentsmax(greedy_fee, best_single_tx_fee)guarantees at least50%of optimal andgreedy_fee >= OPT - max_single_tx_fee. Empirically, replay historical mempool snapshots, compute the exact tree-DP optimum atcapacity = 100, inspect the distribution and p01/worst-case tail ofgreedy_fee / optimal_fee, and benchmark wall-clock latency at10^5–10^6transactions to prove block-template assembly finishes in milliseconds.
Follow-up questions
- Suppose a low-fee parent has multiple children whose individual fees are too modest to justify the parent alone, yet together their combined fees would. Does ancestor-only scoring pick them, and how would you extend it to handle shared-parent families?
- If transactions stream into the mempool continuously across many blocks, how would you maintain package scores incrementally rather than recomputing from scratch each block?
- If you needed the exact maximum possible fee for capacity 100 instead of a greedy approximation, how would you solve it both without dependencies and on parent trees, and what is the runtime?
- How would you validate both theoretically and empirically that this greedy heuristic performs close to optimal on real workloads?
Similar questions
- In-Memory Task Tracker with Assignment and Deadline Queries
- Fixing and Extending an In-Memory Query Cursor
- Expiring Task Assignments with User Quotas
- Timestamped Credit Ledger with Scheduled Rebates and Account Mergers
- Backward-Compatible Composite Keyset Pagination
- Scheduled Transfers and Account Merging Ledger
More Coinbase interview questions
- Key-Value Store with Prefix Scans, Expirations, and Snapshots Medium
- Greedy Block Packing with Ancestor Fee Packages Medium
- Staff-Level Frontend Architecture Deep Dive Hard Pro
- Regional Adoption Rates and Cross-Region Activity Medium Pro
- Marketplace Basket Routing and Windowed Analytics Medium Pro
- Fixing and Extending an In-Memory Query Cursor Hard Pro
- Balancing Delivery Speed Against Automated Test Rigor Medium Pro
- Presenting a Well-Crafted Software Component Medium Pro
- Cryptocurrency Order Placement and Routing Hard Pro
- Web Trading Terminal Frontend Architecture Hard Pro