Greedy Block Packing with Ancestor Fee Packages

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

A block producer selects pending transactions from an unconfirmed pool (mempool) to pack into a single block of fixed byte capacity block_size (default B = 100). Every entry in mempool is an instance of Transaction:

  • id: unique hashable identifier
  • fee: non-negative integer reward earned when the transaction is packed
  • size: positive integer capacity consumed inside the block
  • parent_id: optional identifier of an unconfirmed prerequisite transaction (None when all prerequisites are already confirmed)

Because real pools can hold hundreds of thousands of entries, exact subset-sum optimization is not required; instead, implement a fast deterministic greedy packer across three milestones.

Part 1 — Standalone Greedy Packing (mine_block_simple)

Implement mine_block_simple(mempool: List[Transaction], block_size: int = B) -> List[Transaction].

Ignore parent_id for this milestone. Rank all transactions once by exact fee density fee / size from highest to lowest, breaking exact density ties in favor of the transaction appearing at a smaller index in mempool. Walk that ranked list from front to back: whenever a candidate's size fits within the remaining capacity, append it to the output list and subtract size from the remaining capacity; when a candidate exceeds the remaining capacity, skip past it and keep checking subsequent entries. Return the chosen transactions in selection order.

Part 2 — Dependency Chains and Ancestor Packages (mine_block)

Implement mine_block(mempool: List[Transaction], block_size: int = B) -> List[Transaction].

Now enforce parent_id dependencies (the dependency graph has at most one parent per transaction and contains no cycles, though several children may reference the same parent):

  • When parent_id is None, the transaction has no unconfirmed dependency.
  • When parent_id is non-None and matches no id in mempool, that transaction (an orphan) and all of its descendants are ineligible for packing.
  • Otherwise, the referenced parent must appear earlier in the same returned block whenever the child is selected.

To capture Child-Pays-For-Parent (CPFP) incentives—where a high-fee child compensates for a low-fee ancestor chain—score each eligible unpicked transaction t by its current ancestor package: t together with all of its ancestors in mempool that have not yet been added to the block. Define the package's exact rational fee density as (sum of fees in package) / (sum of sizes in package).

Repeatedly pick the unpicked eligible transaction whose current ancestor package fits within the remaining capacity (package_size <= remaining_capacity) and achieves the highest package fee density, breaking exact ties by smaller mempool index of t itself. Append all unpicked transactions in that package to the block from oldest ancestor down to t, deduct their sizes from remaining capacity, and update the remaining package totals of any unpicked descendants that shared those newly packed ancestors before selecting the next package. Stop when no eligible package fits.

Part 3 — Threshold Fee for a New Child (min_fee)

Implement min_fee(mempool: List[Transaction], parent_id: Hashable, child_size: int, block_size: int = B) -> Optional[int].

Suppose a user wants to append a brand-new child transaction at the end of mempool (with size child_size, parent_id=parent_id, and a fresh unique id, meaning it loses exact density ties against existing pool entries). Return the smallest integer fee >= 0 for which mine_block(mempool + [child], block_size) includes this new child (and therefore parent_id and any unconfirmed ancestors). Return None when no non-negative fee can achieve inclusion (for instance, child_size <= 0, parent_id is missing or orphaned, or child_size plus parent_id's ancestor chain exceeds block_size).

Examples

Example 1

Input:  block_size = 12
        mempool = [
            Transaction("t1", fee=12, size=12),
            Transaction("t2", fee=9,  size=3),
            Transaction("t3", fee=10, size=5),
            Transaction("t4", fee=4,  size=4),
        ]
Call:   mine_block_simple(mempool, block_size=12)
Output: [Transaction("t2", ...), Transaction("t3", ...), Transaction("t4", ...)]

Walk-through: Fee densities are "t2" (9/3 = 3.0), "t3" (10/5 = 2.0), "t1" (12/12 = 1.0, index 0), and "t4" (4/4 = 1.0, index 3). Packing "t2" and "t3" uses 3 + 5 = 8 units (4 left); "t1" needs 12 > 4 and is skipped; "t4" uses the final 4 units for total fee 23.

Example 2

Input:  block_size = 12
        mempool = [
            Transaction("p",    fee=3,  size=5),
            Transaction("c1",   fee=25, size=2, parent_id="p"),
            Transaction("c2",   fee=12, size=3, parent_id="p"),
            Transaction("solo", fee=10, size=4),
        ]
Call:   mine_block(mempool, block_size=12)
Output: [Transaction("p", ...), Transaction("c1", ...), Transaction("c2", ...)]

Walk-through: Initial package densities are p + c1 (28/7 = 4.0), solo (10/4 = 2.5), p + c2 (15/8 = 1.875), and p (3/5 = 0.6). Round 1 packs ["p", "c1"], leaving 5 units of space. Because "p" is now inside the block, "c2" no longer carries "p", raising "c2"'s package density to 12/3 = 4.0 (> 2.5), so Round 2 packs "c2" (2 units left) and "solo" (size = 4) no longer fits.

Example 3

Input:  block_size = 12
        mempool = [
            Transaction("p",    fee=2,  size=5),
            Transaction("fast", fee=40, size=2),
            Transaction("mid",  fee=20, size=4),
        ]
Call:   min_fee(mempool, parent_id="p", child_size=3, block_size=12)
Output: 39

Walk-through: Packing "p" plus the new 3-unit child requires 5 + 3 = 8 units. "fast" (density = 20.0, size = 2) enters first and leaves 10 >= 8 units, so "fast" does not crowd out the child. However, "mid" (density = 5.0, size = 4) would reduce free space from 10 to 6 < 8. Since the appended child loses ties, (2 + fee) / 8 must strictly exceed 5, giving 2 + fee > 40, or fee = 39.

Constraints

  • 0 <= len(mempool) <= 10^5
  • 0 <= tx.fee <= 10^15 (exact integer/rational density comparison is required; do not rely on 64-bit float division)
  • 1 <= tx.size <= 10^6 and 0 <= block_size <= 10^6 (B = 100 by default)
  • Dependency links have at most one parent_id per transaction and form no cycles; chains may be thousands of transactions deep (avoid recursion limits).

Step-by-step walkthrough

  1. Pin down the clarifying rules before coding

    In a multi-part system coding interview, stating crisp assumptions upfront turns ambiguous edge cases into simple invariants:

    • Sizes and capacity: Transaction size is a positive integer (>= 1), fee is a non-negative integer (>= 0), and any single transaction or ancestor chain larger than block_size (B = 100 by default) can never fit in the block.
    • Tie-breaking: Equal fee rates break ties in favor of the transaction appearing earlier in mempool, making the output deterministic and easy to test.
    • Output order: Any order works in Part 1; in Part 2 every parent must appear before its children in the returned list.
    • Orphans and shared parents: Multiple children may share one parent. If parent_id is None, the parent was already mined in a past block; if parent_id names an ID absent from mempool, that transaction and all of its descendants cannot be mined yet.
    • Part 3 contract: A new child is appended at the end of mempool (so it loses ties), must pull in its parent and all unmined ancestors within block_size, and min_fee returns None when no fee can succeed.
  2. Part 1: rank by exact fee rate and keep scanning past misses

    Selecting a subset of items to maximize value under a capacity limit B is the classic 0/1 knapsack problem. Exact dynamic programming takes O(n * B) time, which works for toy B = 100 but becomes far too slow when real block weights reach millions of units and mempools hold hundreds of thousands of transactions. Because the scarce resource inside a block is space, the right greedy score is fee rate (fee / size — fee earned per unit of block space):

    1. Wrap fee / size in Python's Fraction(fee, size) so comparisons cross-multiply exact integers (a * d vs c * b). Standard float division loses precision above 2^53 (float(2**53 + 1) == float(2**53) is True), which would silently corrupt ordering and tie-breakers on 64-bit fees.
    2. When a candidate has tx.size > room, skip it and keep walking — smaller transactions further down the sorted list can still fill the leftover space!
    block_size = 12
    mempool:  t1(fee=12, size=12, rate=1.00)   t2(9,  3, rate=3.00)
              t3(fee=10, size=5,  rate=2.00)   t4(4,  4, rate=1.00)
    
    Sorted by (-rate, index):  t2 (3.00),  t3 (2.00),  t1 (1.00, idx 0),  t4 (1.00, idx 3)
      1. take t2 (size 3) -> room = 9
      2. take t3 (size 5) -> room = 4
      3. skip t1 (size 12 > 4)
      4. take t4 (size 4) -> room = 0  --> block [t2, t3, t4], total fee = 23 (raw-fee order gives [t1] = 12)
    
    def feerate(fee: int, size: int) -> Fraction:
        """Exact rational fee per unit of size so large 64-bit fees never suffer float rounding."""
        return Fraction(fee, size)
    
    
    def mine_block_simple(mempool: List[Transaction], block_size: int = B) -> List[Transaction]:
        """Sort once by highest fee/size (ties: earlier mempool index) and greedily pack what fits."""
        ranked = []
        for index, tx in enumerate(mempool):
            ranked.append((-feerate(tx.fee, tx.size), index))
        ranked.sort()
    
        block = []
        room = block_size
        for _, index in ranked:
            tx = mempool[index]
            if tx.size <= room:
                block.append(tx)
                room -= tx.size
                if room == 0:
                    break
        return block
    

    Where this heuristic can underperform: if B = 100, a = (fee 2, size 1) has rate 2.0 and b = (fee 100, size 100) has rate 1.0, greedy picks a and leaves 99 units empty for fee 2 instead of 100 (taking the better of the greedy block and the single highest-fee fitting transaction fixes this to guarantee >= 50% of optimal).

  3. Part 2: score ancestor packages iteratively

    Under Child-Pays-For-Parent (CPFP), a miner cannot claim a high-fee child without also mining its low-fee parent (and grandparent, and so on) in the same block. So the true atomic unit a miner buys is the ancestor package: transaction i together with all of its unmined ancestors.

    package_feerate(i) = (sum of fees of i and unmined ancestors) / (sum of sizes of i and unmined ancestors)
    

    Because each transaction has at most one parent_id, dependencies form a forest of trees. We first resolve each parent_id to an array index (>= 0), ROOT (-1), or MISSING (-2), and then compute pkg_fee, pkg_size, and minable top-down using an explicit uncomputed_path list (avoiding recursion so a chain of 10,000 transactions never overflows Python's call stack):

    def parent_indexes(mempool: List[Transaction]) -> List[int]:
        """Map each mempool index i to its parent's index (>= 0), ROOT (-1), or MISSING (-2)."""
        position = {}
        for i, tx in enumerate(mempool):
            position[tx.id] = i
    
        parent_of = []
        for tx in mempool:
            if tx.parent_id is None:
                parent_of.append(ROOT)
            elif tx.parent_id in position:
                parent_of.append(position[tx.parent_id])
            else:
                parent_of.append(MISSING)
        return parent_of
    
    
    def package_totals(mempool: List[Transaction],
                       parent_of: List[int]) -> Tuple[List[int], List[int], List[bool]]:
        """Compute (pkg_fee, pkg_size, minable) for each transaction's full unmined ancestor chain."""
        n = len(mempool)
        pkg_fee = [0] * n
        pkg_size = [0] * n
        minable = [False] * n
        computed = [False] * n
    
        for i in range(n):
            uncomputed_path = []
            curr = i
            while curr >= 0 and not computed[curr]:
                uncomputed_path.append(curr)
                curr = parent_of[curr]
    
            for node in reversed(uncomputed_path):
                parent = parent_of[node]
                if parent == ROOT:
                    pkg_fee[node] = mempool[node].fee
                    pkg_size[node] = mempool[node].size
                    minable[node] = True
                elif parent != MISSING and minable[parent]:
                    pkg_fee[node] = pkg_fee[parent] + mempool[node].fee
                    pkg_size[node] = pkg_size[parent] + mempool[node].size
                    minable[node] = True
                computed[node] = True
    
        return pkg_fee, pkg_size, minable
    
  4. Part 2: re-score sibling branches when shared ancestors enter the block

    Suppose parent p (fee=3, size=5) has two children c1 (25, 2) and c2 (12, 3), alongside an unrelated transaction solo (10, 4) in a block of size 12:

    Round 1 candidate packages:
      p + c1 : (3 + 25) / (5 + 2) = 28 / 7 = 4.00   <-- winner!
      solo   : 10 / 4             = 2.50
      p + c2 : (3 + 12) / (5 + 3) = 15 / 8 = 1.875
    
    We add [p, c1] to the block (room drops from 12 -> 5).
    Now p is ALREADY in the block! So c2 no longer drags p along:
      c2's remaining package is just c2 alone: 12 / 3 = 4.00  >  solo (2.50)!
    Round 2 takes c2 -> block [p, c1, c2], total fee = 40 (stale score 1.875 would pick solo for fee 38).
    

    Look at what happens in the dependency tree whenever an unmined chain chain = [a_0, a_1, ..., a_k] enters the block:

          a_0  (newly mined: dropped = a_0)
         /   \
       a_1   side_branch_0   <-- every node in this subtree loses a_0's (fee, size)
      /   \
    a_k   side_branch_1      <-- every node in this subtree loses (a_0 + a_1)'s (fee, size)
    

    Walking down chain while accumulating (dropped_fee, dropped_size) lets us update every unmined side subtree in one pass per round without touching any node twice!

    def children_lists(parent_of: List[int]) -> List[List[int]]:
        """Build adjacency lists children[p] = list of direct child indexes of p."""
        children = []
        for _ in parent_of:
            children.append([])
        for i, parent in enumerate(parent_of):
            if parent >= 0:
                children[parent].append(i)
        return children
    
    
    def collect_subtree(root: int, children: List[List[int]]) -> List[int]:
        """Return `root` and all of its descendants in the dependency forest (iteratively)."""
        nodes = []
        stack = [root]
        while stack:
            curr = stack.pop()
            nodes.append(curr)
            stack.extend(children[curr])
        return nodes
    
    
    def unmined_chain(i: int, parent_of: List[int], in_block: List[bool]) -> List[int]:
        """Return `i` and its ancestors not yet in the block, ordered oldest-parent-first."""
        chain = []
        curr = i
        while curr >= 0 and not in_block[curr]:
            chain.append(curr)
            curr = parent_of[curr]
        chain.reverse()
        return chain
    
  5. Part 2: assemble the block with a lazy-deletion heap

    To pick the highest-rate package quickly without sorting the entire mempool after every update, we keep (-package_feerate, tx_index) pairs in a heapq priority queue and use lazy deletion: whenever a descendant's package rate changes, we simply push its new (−rate, index) tuple onto the heap, and when popping we ignore entries that are already in_block or whose stored rate no longer matches feerate(pkg_fee[i], pkg_size[i]).

    One subtle invariant makes size filtering exact: can a package that initially exceeds block_size (or exceeds room at some point) ever fit later in the same block after an ancestor a enters the block? No! Mining a shrinks pkg_size[d] by a.size, and shrinks room by the exact same a.size, so room - pkg_size[d] never increases during a block. Thus any entry popped with pkg_size[i] > room can never fit in this block (we only re-push fitting descendants when their fee rate changes).

    def mine_block(mempool: List[Transaction], block_size: int = B) -> List[Transaction]:
        """Repeatedly select the highest-feerate fitting ancestor package (ties: earlier index)."""
        parent_of = parent_indexes(mempool)
        pkg_fee, pkg_size, minable = package_totals(mempool, parent_of)
        children = children_lists(parent_of)
    
        heap = []
        for i in range(len(mempool)):
            if minable[i] and pkg_size[i] <= block_size:
                heap.append((-feerate(pkg_fee[i], pkg_size[i]), i))
        heapq.heapify(heap)
    
        in_block = [False] * len(mempool)
        block = []
        room = block_size
    
        while heap and room > 0:
            neg_rate, i = heapq.heappop(heap)
            if in_block[i] or -neg_rate != feerate(pkg_fee[i], pkg_size[i]):
                continue
            if pkg_size[i] > room:
                continue
    
            chain = unmined_chain(i, parent_of, in_block)
            for ancestor in chain:
                in_block[ancestor] = True
                block.append(mempool[ancestor])
                room -= mempool[ancestor].size
    
            dropped_fee = 0
            dropped_size = 0
            for ancestor in chain:
                dropped_fee += mempool[ancestor].fee
                dropped_size += mempool[ancestor].size
                for child in children[ancestor]:
                    if not in_block[child]:
                        for desc in collect_subtree(child, children):
                            pkg_fee[desc] -= dropped_fee
                            pkg_size[desc] -= dropped_size
                            if pkg_size[desc] <= room:
                                heapq.heappush(heap, (-feerate(pkg_fee[desc], pkg_size[desc]), desc))
    
        return block
    
  6. Part 3: prove monotonicity and binary-search the minimum child fee

    In Part 3, we append a brand-new leaf transaction child (with parent_id and child_size) at the end of mempool and want the smallest non-negative integer fee such that mine_block(mempool + [child]) includes child.

    Instead of hand-crafting fragile casework (because small high-rate rivals can sit beside child's package without blocking it!), notice two clean properties:

    1. Monotonicity: Because child is a leaf with no descendants, raising child.fee from f to f' > f boosts only child's own package rate while leaving every other package unchanged. Compared with the run at f (assuming f succeeds in round R), the run at f' either selects child's package even earlier (before round R, when room is at least as large) or makes the identical choices through round R - 1 and selects child's package in round R. So inclusion transitions cleanly from False to True at a single threshold!
    2. Guaranteed upper bound: When need = pkg_size[parent] + child_size <= block_size, every rival package has size >= 1 and fee <= total_fee = sum(tx.fee for tx in mempool), so its fee rate is <= total_fee. Setting hi = total_fee * need + 1 gives child's package a rate >= (total_fee * need + 1) / need > total_fee, guaranteeing it wins round 1!
    block_size = 12,  mempool = [p(fee=2, size=5), fast(fee=40, size=2), mid(fee=20, size=4)],  child_size = 3
    need = size(p) + child_size = 5 + 3 = 8 <= 12.
      - Rival fast (rate 20, size 2) goes first, leaving room = 10 >= 8 (fast does NOT block us!).
      - Rival mid  (rate  5, size 4) WOULD reduce room from 10 -> 6 < 8!
      - Since child is appended last (loses ties), we need (2 + fee) / 8 > 5  =>  2 + fee > 40  =>  fee = 39.
    Binary search over [0, 62*8 + 1] finds hi = 39 automatically!
    
    def child_included(mempool: List[Transaction], parent_id: Hashable, child_size: int,
                       fee: int, block_size: int) -> bool:
        """Return True if appending a new child with `fee` causes `mine_block` to include it."""
        child = Transaction(id=object(), fee=fee, size=child_size, parent_id=parent_id)
        for tx in mine_block(mempool + [child], block_size):
            if tx is child:
                return True
        return False
    
    
    def min_fee(mempool: List[Transaction], parent_id: Hashable, child_size: int,
                block_size: int = B) -> Optional[int]:
        """Smallest integer fee >= 0 that pulls both `parent_id` (and its ancestors) and the new
        child into `mine_block(mempool + [child])`, or None if impossible."""
        parent_of = parent_indexes(mempool)
        _, pkg_size, minable = package_totals(mempool, parent_of)
    
        parent_idx = None
        for i, tx in enumerate(mempool):
            if tx.id == parent_id:
                parent_idx = i
        if parent_idx is None or not minable[parent_idx] or child_size <= 0:
            return None
    
        need = pkg_size[parent_idx] + child_size
        if need > block_size:
            return None
        if child_included(mempool, parent_id, child_size, 0, block_size):
            return 0
    
        total_fee = 0
        for tx in mempool:
            total_fee += tx.fee
    
        lo = 0
        hi = total_fee * need + 1
        while hi - lo > 1:
            mid = (lo + hi) // 2
            if child_included(mempool, parent_id, child_size, mid, block_size):
                hi = mid
            else:
                lo = mid
        return hi
    
  7. Complete solution

    Putting Parts 1, 2, and 3 together into solution.py:

    from dataclasses import dataclass
    from fractions import Fraction
    from typing import Hashable, List, Optional, Tuple
    import heapq
    
    B = 100         # default block capacity in size units
    
    ROOT = -1       # transaction has no parent_id (its parent is already mined in an earlier block)
    MISSING = -2    # parent_id is non-None, but no transaction with that ID exists in `mempool`
    
    
    @dataclass
    class Transaction:
        id: Hashable
        fee: int                        # non-negative integer fee paid to the miner
        size: int                       # positive integer block space consumed
        parent_id: Optional[Hashable] = None
    
    
    def feerate(fee: int, size: int) -> Fraction:
        """Exact rational fee per unit of size so large 64-bit fees never suffer float rounding."""
        return Fraction(fee, size)
    
    
    # ---- Part 1: greedy selection by fee rate (ignoring parent links) ---------------------------
    
    def mine_block_simple(mempool: List[Transaction], block_size: int = B) -> List[Transaction]:
        """Sort once by highest fee/size (ties: earlier mempool index) and greedily pack what fits."""
        # ranked: list of (-fee_rate, mempool_index) tuples; negating fee_rate puts highest rates
        # first while keeping smaller `mempool_index` first on exact ties.
        ranked = []
        for index, tx in enumerate(mempool):
            ranked.append((-feerate(tx.fee, tx.size), index))
        ranked.sort()
    
        block = []
        room = block_size
        for _, index in ranked:
            tx = mempool[index]
            # Skip oversized transactions instead of stopping: a smaller transaction later may fit!
            if tx.size <= room:
                block.append(tx)
                room -= tx.size
                if room == 0:
                    break
        return block
    
    
    # ---- Part 2: ancestor packages and Child-Pays-For-Parent (CPFP) -----------------------------
    
    def parent_indexes(mempool: List[Transaction]) -> List[int]:
        """Map each mempool index i to its parent's index (>= 0), ROOT (-1), or MISSING (-2)."""
        # position: dict mapping tx.id -> index in `mempool`
        position = {}
        for i, tx in enumerate(mempool):
            position[tx.id] = i
    
        parent_of = []
        for tx in mempool:
            if tx.parent_id is None:
                parent_of.append(ROOT)
            elif tx.parent_id in position:
                parent_of.append(position[tx.parent_id])
            else:
                parent_of.append(MISSING)
        return parent_of
    
    
    def package_totals(mempool: List[Transaction],
                       parent_of: List[int]) -> Tuple[List[int], List[int], List[bool]]:
        """Compute (pkg_fee, pkg_size, minable) for each transaction's full unmined ancestor chain.
    
        Uses an explicit path list rather than recursion so deep chains cannot hit RecursionError.
        """
        n = len(mempool)
        pkg_fee = [0] * n       # pkg_fee[i]: sum of fees of i and all its mempool ancestors
        pkg_size = [0] * n      # pkg_size[i]: sum of sizes of i and all its mempool ancestors
        minable = [False] * n   # minable[i]: True iff i's ancestor chain ends at ROOT (not MISSING)
        computed = [False] * n
    
        for i in range(n):
            # Walk upward from `i` until hitting ROOT, MISSING, or an ancestor already computed.
            uncomputed_path = []
            curr = i
            while curr >= 0 and not computed[curr]:
                uncomputed_path.append(curr)
                curr = parent_of[curr]
    
            # Fill totals top-down from oldest ancestor down to `i`.
            for node in reversed(uncomputed_path):
                parent = parent_of[node]
                if parent == ROOT:
                    pkg_fee[node] = mempool[node].fee
                    pkg_size[node] = mempool[node].size
                    minable[node] = True
                elif parent != MISSING and minable[parent]:
                    pkg_fee[node] = pkg_fee[parent] + mempool[node].fee
                    pkg_size[node] = pkg_size[parent] + mempool[node].size
                    minable[node] = True
                computed[node] = True
    
        return pkg_fee, pkg_size, minable
    
    
    def children_lists(parent_of: List[int]) -> List[List[int]]:
        """Build adjacency lists children[p] = list of direct child indexes of p."""
        children = []
        for _ in parent_of:
            children.append([])
        for i, parent in enumerate(parent_of):
            if parent >= 0:
                children[parent].append(i)
        return children
    
    
    def collect_subtree(root: int, children: List[List[int]]) -> List[int]:
        """Return `root` and all of its descendants in the dependency forest (iteratively)."""
        nodes = []
        stack = [root]
        while stack:
            curr = stack.pop()
            nodes.append(curr)
            stack.extend(children[curr])
        return nodes
    
    
    def unmined_chain(i: int, parent_of: List[int], in_block: List[bool]) -> List[int]:
        """Return `i` and its ancestors not yet in the block, ordered oldest-parent-first."""
        chain = []
        curr = i
        while curr >= 0 and not in_block[curr]:
            chain.append(curr)
            curr = parent_of[curr]
        chain.reverse()
        return chain
    
    
    def mine_block(mempool: List[Transaction], block_size: int = B) -> List[Transaction]:
        """Repeatedly select the highest-feerate fitting ancestor package (ties: earlier index).
    
        Whenever a chain of transactions enters the block, any unmined branches hanging off that
        chain no longer have to pay for those newly mined ancestors, so their packages shrink and
        their updated fee rates are pushed onto the heap.
        """
        parent_of = parent_indexes(mempool)
        pkg_fee, pkg_size, minable = package_totals(mempool, parent_of)
        children = children_lists(parent_of)
    
        # heap: min-heap of (-package_feerate, tx_index) acting as a max-heap on fee rate.
        # Any package initially larger than `block_size` can never fit in this block even if its
        # ancestors are mined first, because mining an ancestor reduces `room` and `pkg_size` equally.
        heap = []
        for i in range(len(mempool)):
            if minable[i] and pkg_size[i] <= block_size:
                heap.append((-feerate(pkg_fee[i], pkg_size[i]), i))
        heapq.heapify(heap)
    
        in_block = [False] * len(mempool)
        block = []
        room = block_size
    
        while heap and room > 0:
            neg_rate, i = heapq.heappop(heap)
            # Lazy deletion: ignore entries already pulled in as an ancestor, or stale entries
            # whose rate was superseded when an ancestor entered the block earlier.
            if in_block[i] or -neg_rate != feerate(pkg_fee[i], pkg_size[i]):
                continue
            # Once `pkg_size[i] > room`, `room - pkg_size[i]` can never increase in this block.
            if pkg_size[i] > room:
                continue
    
            # Phase 1: Append unmined ancestors oldest-first so parents always precede children.
            chain = unmined_chain(i, parent_of, in_block)
            for ancestor in chain:
                in_block[ancestor] = True
                block.append(mempool[ancestor])
                room -= mempool[ancestor].size
    
            # Phase 2: Update unmined sibling/descendant subtrees hanging off `chain` in one pass.
            # An off-chain branch below `chain[k]` loses the combined fee and size of `chain[0..k]`.
            dropped_fee = 0
            dropped_size = 0
            for ancestor in chain:
                dropped_fee += mempool[ancestor].fee
                dropped_size += mempool[ancestor].size
                for child in children[ancestor]:
                    if not in_block[child]:
                        for desc in collect_subtree(child, children):
                            pkg_fee[desc] -= dropped_fee
                            pkg_size[desc] -= dropped_size
                            if pkg_size[desc] <= room:
                                heapq.heappush(heap, (-feerate(pkg_fee[desc], pkg_size[desc]), desc))
    
        return block
    
    
    # ---- Part 3: minimum fee for a new child to get mined with its parent -----------------------
    
    def child_included(mempool: List[Transaction], parent_id: Hashable, child_size: int,
                       fee: int, block_size: int) -> bool:
        """Return True if appending a new child with `fee` causes `mine_block` to include it."""
        # `object()` creates a unique sentinel ID that cannot collide with any existing tx.id.
        # Appending at the end means the new child loses exact fee-rate ties to existing txs.
        child = Transaction(id=object(), fee=fee, size=child_size, parent_id=parent_id)
        for tx in mine_block(mempool + [child], block_size):
            if tx is child:
                return True
        return False
    
    
    def min_fee(mempool: List[Transaction], parent_id: Hashable, child_size: int,
                block_size: int = B) -> Optional[int]:
        """Smallest integer fee >= 0 that pulls both `parent_id` (and its ancestors) and the new
        child into `mine_block(mempool + [child])`, or None if impossible."""
        parent_of = parent_indexes(mempool)
        _, pkg_size, minable = package_totals(mempool, parent_of)
    
        parent_idx = None
        for i, tx in enumerate(mempool):
            if tx.id == parent_id:
                parent_idx = i
        if parent_idx is None or not minable[parent_idx] or child_size <= 0:
            return None
    
        # `need` is the combined block space of the parent's unmined ancestor chain plus the child.
        need = pkg_size[parent_idx] + child_size
        if need > block_size:
            return None
        if child_included(mempool, parent_id, child_size, 0, block_size):
            return 0
    
        # Upper bound proof: every existing package has size >= 1 and fee <= total_fee, so its
        # fee rate is <= total_fee. Setting fee = total_fee * need + 1 gives the child's package
        # rate >= (total_fee * need + 1) / need > total_fee, strictly beating every rival in round 1.
        total_fee = 0
        for tx in mempool:
            total_fee += tx.fee
    
        # Invariant: `lo` is known to NOT include `child`; `hi` is known to include `child`.
        lo = 0
        hi = total_fee * need + 1
        while hi - lo > 1:
            mid = (lo + hi) // 2
            if child_included(mempool, parent_id, child_size, mid, block_size):
                hi = mid
            else:
                lo = mid
        return hi
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine loading a delivery van with B = 100 cubic feet of space where each package pays you a flat fee: because space is what runs out, you earn the most per cubic foot by sorting items by fee rate (fee / size — dollars earned per unit of space) and loading every item that still fits. When a high-paying item (child) legally requires an earlier low-paying item (parent) to ride ahead of it in the same van — a mechanism called Child-Pays-For-Parent (CPFP) — you cannot buy the child alone; instead, you score each transaction as an ancestor package (the transaction bundled with all of its unmined ancestors) using combined_fee / combined_size. Crucially, as soon as one child pulls that shared parent into the van, any sibling children waiting on the same parent no longer have to carry the parent's dead weight, so their remaining packages shrink and get re-scored at their own higher fee rates!

Why do simpler approaches fail? Picking transactions with the largest raw fee lets a single 100-unit, 50-fee giant crowd out fifty 2-unit, 3-fee transactions (150 in fees). Exact 0/1 knapsack dynamic programming (finding the highest-value subset under a weight limit) scales with block capacity O(n * B), which is far too slow on real cryptocurrency blocks with millions of weight units and huge mempools. And in Part 2, scoring children individually produces invalid blocks (missing parents) or terrible deals (a tiny rich child dragging in a huge 0-fee parent), while computing package scores only once at the start under-ranks sibling transactions after their shared parent has already been mined.

Walk through a 4-transaction mempool with block_size = 12: parent p(fee=3, size=5), its two children c1(25, 2) and c2(12, 3), and standalone solo(10, 4):

Initial packages:
  pkg(c1)   = p + c1 -> fee 28, size 7, rate 28/7 = 4.00   (highest!)
  pkg(solo) = solo   -> fee 10, size 4, rate 10/4 = 2.50
  pkg(c2)   = p + c2 -> fee 15, size 8, rate 15/8 = 1.875
  pkg(p)    = p      -> fee  3, size 5, rate  3/5 = 0.60

Step 1: Pop pkg(c1), append [p, c1] oldest-first -> room = 12 - 7 = 5.
Step 2: Because p is now in the block, subtract p(3, 5) from unmined sibling c2:
        pkg(c2) becomes c2 alone -> fee 12, size 3, rate 12/3 = 4.00! Push (c2, rate 4.00) to heap.
Step 3: Pop updated pkg(c2) (rate 4.00 > solo's 2.50), append [c2] -> room = 5 - 3 = 2.
Step 4: Pop pkg(solo) (size 4 > room 2, skip) -> final block [p, c1, c2], total fee = 40.

Complexity

Let n = len(mempool), B = block_size, and U be the total number of descendant re-scorings across all rounds of mine_block.

  • Part 1 (mine_block_simple):
    • Time: O(n log n). Building the ranked list takes O(n), sorting n exact Fraction rates takes O(n log n) (since size <= B or small integers keep rational cross-multiplication O(1)), and scanning ranked visits each transaction at most once in O(n). (Using heapq.heapify instead of sorting reduces this to O(n + p log n) when the block fills after p pops.)
    • Space: O(n) to hold the ranked tuple list and the returned block (at most B transactions).
  • Part 2 (mine_block):
    • Time: O((n + U) log n). Indexing IDs, computing package_totals top-down, building children_lists, and calling heapq.heapify each visit every node once in O(n) time. Each round pops stale/oversized heap entries and, when a chain enters the block, updates each affected unmined descendant once for that round and pushes at most U new heap entries (O(log n) per push/pop). Since at most B rounds can add transactions (size >= 1), U is at most (number of rounds) * (max subtree size) <= B * n, and in typical mempools with bounded family sizes U is O(B).
    • Space: O(n + U) for the O(n) per-transaction arrays (parent_of, pkg_fee, pkg_size, minable, children, in_block) plus at most n + U live and stale entries in the min-heap (a binary tree stored in an array that pops the smallest key — here the most negative fee rate — in O(log size) time).
  • Part 3 (min_fee):
    • Time: O(log(total_fee * need) * T_mine), where T_mine is one mine_block call on n + 1 transactions. Binary search (repeatedly halving [lo, hi]) runs mine_block once at fee = 0 and ceil(log2(total_fee * need + 1)) times inside the loop — at most 71 calls even if total_fee reaches 2^64 and need <= 100.
    • Space: O(n + U) per mine_block probe, as each probe discards its temporary state upon returning.

Edge cases

  • Empty mempool or block_size == 0: Both mine_block_simple and mine_block cleanly return [].
  • Oversized transactions and packages (pkg_size[i] > block_size): Never enter the heap, and never become valid later in the same block even if an ancestor is mined first — because mining ancestor a reduces pkg_size[d] by a.size and reduces room by a.size, keeping room - pkg_size[d] negative!
  • Orphaned chains (parent_id missing from mempool): Marked MISSING; both the transaction and all of its descendants get minable = False regardless of how high their fees are.
  • Zero-fee transactions (fee == 0): Have exact rate 0 and are still included if block space remains after positive-rate packages.
  • Very deep parent chains: package_totals, collect_subtree, and unmined_chain all use iterative loops/stacks rather than recursion, preventing RecursionError on chains thousands of links long.
  • Part 3 boundary cases: Returns 0 when the child already makes the block at fee = 0; returns None when parent_id is absent or orphaned, child_size <= 0, or pkg_size[parent] + child_size > block_size. Note that in a fixed-width uint64 language (C++/Rust), total_fee * need can exceed 2^64 - 1 when rivals have huge fees, requiring 128-bit intermediate arithmetic and overflow checks.

Common mistakes

  • Sorting by raw fee instead of fee / size: Wastes scarce block space on bulky low-density transactions.
  • Breaking out of the loop on the first candidate that doesn't fit: Leaves leftover capacity unused when smaller transactions further down the sorted list still fit.
  • Comparing fee rates with float: Two distinct 64-bit integer ratios above 2^53 round to the exact same double, silently breaking rate order and deterministic tie-breaking; always cross-multiply integers (as Fraction does).
  • Forgetting lazy deletion or sibling updates in Part 2: Leaving old heap entries active without verifying -neg_rate == feerate(pkg_fee[i], pkg_size[i]), or failing to subtract newly mined ancestors from sibling subtrees.
  • Outputting children before parents or duplicating shared parents: Always walk unmined_chain up to the first in_block ancestor and reverse it so only unmined ancestors are appended, oldest-parent-first.
  • Assuming Part 3 must beat the highest rate in the mempool: A tiny ultra-high-rate transaction (size = 2, rate = 25) can sit comfortably beside a 6-unit child package inside a 10-unit block! Only rivals that actually crowd out the 6-unit package must be outranked, which binary search over mine_block handles automatically.

Alternative approaches

  • Exact 0/1 knapsack for Part 1 when B is a small integer (B = 100): At most floor(B / s) transactions of size s can ever fit in a block of size B, so keeping only the top floor(100 / s) highest-fee transactions per size s in 1..100 shrinks any massive mempool down to at most sum(100 // s for s in range(1, 101)) = 482 candidates in one streaming pass! Running standard O(candidates * B) knapsack DP on those <= 482 items takes <= 48,200 operations and finds the exact optimum.

python def best_fee_exact(candidates, block_size): best = [0] * (block_size + 1) # best[c] = max fee achievable using <= c size units for tx in candidates: for cap in range(block_size, tx.size - 1, -1): if best[cap - tx.size] + tx.fee > best[cap]: best[cap] = best[cap - tx.size] + tx.fee return best[block_size]

  • 1/2-approximation safeguard for Part 1: Compute both the greedy fee-rate block and the best single fitting transaction (size <= B), and return whichever pays more. Because greedy's prefix before the first skipped item plus that skipped item exceeds the fractional optimum, the larger of those two is guaranteed to collect at least 50% of the true optimal fee.

Follow-up questions

  • When pending transactions arrive and confirm in a live stream across consecutive blocks, how can you keep ancestor-package rates updated dynamically rather than rebuilding state on each call? Maintain pkg_fee, pkg_size, and an ordered index (such as a balanced tree or indexed heap keyed by (feerate, arrival_seq)) persistently inside the mempool data structure as transactions arrive and leave: admitting a new child reads its parent's totals in O(1), and confirming or evicting a root subtracts its (fee, size) from its descendants. During mine_block, never mutate the live mempool index — instead keep a small per-block hash map (overlay) of descendants modified during this block assembly, and at each step pop whichever has the higher rate between overlay and the live index (skipping live entries superseded by overlay or in_block). Real systems like Bitcoin Core also cap ancestor/descendant package counts (for example, <= 25 transactions) at mempool admission so every incremental update is O(1) bounded.
  • Suppose a single transaction may depend on two or more unconfirmed parents, turning the forest into a general DAG. Where does tree-based package accounting fail, and how do you fix it? In a DAG (directed acyclic graph — a dependency graph without cycles where a child can have multiple parents that share a common grandparent, forming a diamond), adding pkg_fee[p1] + pkg_fee[p2] double-counts the shared grandparent! Instead, each transaction's ancestor package must be computed as the set union of its ancestor graph via breadth-first or depth-first search with a visited set, and adding a package to the block must emit its unmined ancestors in topological order (an ordering where every parent appears before all of its children) while subtracting each newly mined node at most once from each unmined descendant. Notice that ancestor-at-a-time scoring is still a heuristic on DAGs (for instance, two siblings might jointly justify a heavy parent that neither justifies alone).
  • How would you quantify the revenue gap between your greedy packer and the true theoretical optimum on real workloads? Capture historical mempool snapshots and compare sum(tx.fee for tx in mine_block(snapshot)) against an offline exact solver: for Part 1 with small B, use the pruned O(B log B * B) 0/1 knapsack DP; for Part 2 on single-parent trees, use a tree-knapsack dynamic program (O(n * B²) merging child subtrees into parent capacities); and for general multi-parent DAGs or large B, formulate an integer linear program (ILP) (x_i in {0, 1}, sum(size_i * x_i) <= B, x_child <= x_parent) or compare against the cheap fractional-knapsack upper bound when ILP times out. Track the relative optimality gap (optimal - heuristic) / optimal across both the mean and tail percentiles (p95, p99) so rare adversarial cases aren't hidden by easy snapshots.

Follow-up questions

Similar questions

More Coinbase interview questions

All 99 Coinbase questions →