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" (int or float, >= 0): fee earned by the miner if this transaction is included.
  • "size" (int, >= 1): block capacity consumed by this transaction.
  • "parent_id" (optional str or None): when present, non-None, and equal to the "id" of another entry in txs, 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 from txs, 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:

  1. At any moment, an unselected transaction x's ancestor package consists of x plus 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 in txs.
  2. 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.
  3. Return the selected transaction "id" strings in valid parent-before-child order: scan txs in 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 (70 capacity left); "tx_d" exceeds 100 and is skipped; "tx_a" enters next (30 capacity left); "tx_b" needs 75 > 30 and is skipped; "tx_e" fits in 25 <= 30 and enters. Emitting the chosen IDs in input order gives ["tx_a", "tx_c", "tx_e"] (total size 95, total fee 76).

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 scores 2 / 25 = 0.08, "solo" scores 35 / 50 = 0.70, "child_2" with "root_p" scores 20 / 45 = 0.44, and "child_1" with "root_p" leads at (2 + 44) / (25 + 15) = 1.15. Selecting ["root_p", "child_1"] uses 40 space (40 left) and removes "root_p" from sibling "child_2"'s package, raising "child_2" to 18 / 20 = 0.90 ahead of "solo" (0.70, which also exceeds the remaining 40 space). Because "child_1" appears at index 0 in txs, its required parent "root_p" is emitted right before it, yielding ["root_p", "child_1", "child_2"].

Constraints

  • 0 <= len(txs) <= 100,000
  • 0 <= capacity <= 10,000 (default 100)
  • All "id" strings in txs are unique; "fee" >= 0 and "size" >= 1
  • Every transaction has at most one "parent_id", and parent dependencies form an acyclic forest

Step-by-step walkthrough

  1. 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 (or capacity). Each transaction dict has id, fee, size, and (from Part 2 onward) an optional parent_id. We must return a list of chosen transaction IDs such that:

    • Their combined size is at most capacity.
    • Whenever a transaction is chosen, every unmined ancestor it depends on is also chosen and appears earlier in the output list.
    • Total collected fee is 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:

    • size is a positive integer (>= 1) and fee is a non-negative number (>= 0). Any transaction or chain with size > capacity is simply skipped.
    • A missing parent_id, None, or a parent_id not present in txs means 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 in txs.
  2. 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 45 for 75 units earns only 0.60 per unit, whereas two smaller ones paying 36 (size 30, rate 1.20) and 28 (size 40, rate 0.70) earn 64 in just 70 units!

    So in Part 1 (no parents), rank transactions by fee rate fee / size from highest to lowest. When the next candidate is larger than remaining_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 least OPT - max_single_fee, because right before the first skipped item X, greedy holds the exact prefix that fractional knapsack would pick, so greedy_so_far + fee(X) >= OPT. When individual transactions are small relative to the block, that gap is tiny.

  3. Part 2: score ancestor packages and update descendants

    With parent dependencies, you cannot legally pick a child c without also picking its unmined parent p (and p's unmined parent g, and so on). Child-pays-for-parent (CPFP) happens when p has 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 x by its ancestor package — x plus 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 children A (fee 50, size 10) and B (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!
    
  4. 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 up parent pointers only until hitting -1 or an ancestor whose package was already computed (computed[curr] == True). Then walk that short path in reverse (oldest ancestor down to start), adding each parent's already-known package totals to its child. Every transaction is computed once in O(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 result
    
  5. Select packages with a lazy max-heap

    Python's heapq is a min-heap and does not support modifying priorities in place. We use lazy invalidation with a version array:

    • Push (-rate, i, version[i]). Negating rate pops the highest fee rate first, and i breaks ties in favor of earlier input positions.
    • When i's package fits in remaining_room, mark every transaction anc in _unmined_chain(i, ...) as in_block[anc] = True.
    • For every unchosen descendant desc of each newly added anc, subtract fee[anc] and size[anc] from desc's package. Then increment version[desc] and push a fresh heap tuple (-new_rate, desc, version[desc]).
    • Whenever an old heap tuple pops with pushed_ver != version[i] (or in_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)]
    
  6. 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 filtering txs in raw input order would fail whenever a child appeared before its parent in txs!

    _block_order combines both requirements cleanly: scan i from 0 to n - 1. Whenever i was chosen and not yet emitted, walk up i'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 order
    
  7. Trace 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 X of size s under parent P so both P and X enter the next block: first check whether pkg_size[P] + s > capacity (impossible at any fee). Otherwise, because X has no children of its own, raising X's fee monotonically improves X's package rate without hurting it, so you can test fee 0 first and otherwise binary-search f in [0, total_mempool_fee * (pkg_size[P] + s) + 1] in O(log F) calls to select_transactions.

  8. 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):

  1. Initial packages: P scores 0 / 40 = 0.00, A scores (0 + 50) / (40 + 10) = 1.00, Z scores 28 / 45 = 0.62, and B scores (0 + 30) / (40 + 10) = 0.60.
  2. Pop A (rate 1.00): Its missing chain [P, A] has size 50 <= 100, leaving 50 room. Now P is in the block, so B drops P's 0 fee and 40 size: B's package becomes 30 / 10 = 3.00 (version[B] = 1) and is pushed onto the heap.
  3. Pop B (rate 3.00, v1): Size 10 <= 50 fits, leaving 40 room.
  4. Finish: Z (size 45 > 40) does not fit and is skipped; stale B (v0) and already-included P are skipped. Outputting in topological order (every parent listed before its children while respecting input order otherwise) returns ['P', 'A', 'B'] for total fee 80.

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). Building index_of, parent, and children scans the n transactions once (O(n)). _initial_packages visits each transaction once via memoized parent walks (O(n)), and heapq.heapify builds the initial heap in O(n). The selection loop pushes n initial entries plus U updated entries, and each push or pop on a heap of size at most n + U takes O(log(n + U)) = O(log n) time. Finally, _block_order visits each transaction at most once (O(n)). When there are no parents (U = 0), this simplifies to O(n log n); in real mempools unconfirmed ancestor/descendant chains are capped at small constants (for example 25 in Bitcoin Core), keeping U tiny (O(A * max_descendants)), whereas a single pathological chain of length n has worst-case U <= A * n.
  • Space: O(n + U). The arrays fee, size, parent, children, pkg_fee, pkg_size, version, and in_block each hold O(n) items, and the heap holds at most n + U tuples 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_room skips the oversized package without halting the loop; notably, if [parent, child] exceeds capacity (60 + 50 = 110 > 100), parent alone (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_id missing, None, or absent from txs: Treated as an already-mined parent (parent[i] = -1), imposing zero size overhead or ordering constraint.
  • Child appears before its parent in txs: _block_order walks upward from the child and emits all unemitted chosen ancestors first, guaranteeing parent-before-child validity.
  • Zero-fee transactions: Score 0.0 on 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,000 levels): Every upward and downward traversal (_initial_packages, _unmined_chain, _descendants, _block_order) uses explicit loops/stacks so Python never raises RecursionError.

Common mistakes

  • Breaking out of the loop at the first transaction that exceeds remaining_room: In Example 1, after "tx_c" and "tx_a" consume 70 units, stopping when "tx_b" (size 75 > 30) pops would miss "tx_e" (size 25 <= 30) right behind it.
  • Scoring children by individual fee / size instead of ancestor-package rate: Either produces an invalid block (missing unmined parents), fails CPFP (never mines a 0-fee parent), or lets a tiny high-fee child (fee 20, size 10) drag in a massive 0-fee parent (size 90) for a poor 0.20 combined rate.
  • Forgetting to rescore siblings when a shared parent enters the block: Leaving P's size inside sibling B's package makes B look artificially weak (0.60 instead of 3.00).
  • Sorting chosen IDs strictly by input index at the end: Fails whenever txs lists a child at index 0 and its parent at index 3.
  • Recomputing ancestor sums up to the root from scratch for every transaction: Turns O(n) initialization into O(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 capacity to maximize value. Keeping an array dp[c] for the best fee using at most c size units updates in O(n * capacity) = O(100 * n) time — linear in n because capacity = 100 is 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 in O(n log n) time and O(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 if P has fee 0, size 40 and two children each have fee 20, size 10, each single-child package scores 20 / 50 = 0.40 and loses to 0.50 competitors even though [P, child_1, child_2] together score 40 / 60 = 0.67! To capture multi-child CPFP on trees, also generate a family candidate for each parent P by sorting P's children in descending order of individual fee rate and greedily absorbing children as long as a child's rate exceeds the running combined rate F / S (since (F + f) / (S + s) > F / S if and only if f / 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, and pkg_size persistently across blocks, paired with a balanced sorted set (or indexed priority queue) keyed by (-pkg_rate, id). When a new transaction X arrives, its initial package is simply (fee[X], size[X]) plus its parent's current package in O(1) time, inserted into the sorted set in O(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] for c = 0..100 in O(n * capacity) = O(100 * n) time. With single-parent dependencies (a forest), flatten the forest in DFS preorder so every node k's subtree occupies a contiguous slice [k .. end[k] - 1], and define dp[k][c] as the maximum fee achievable from index k onward with c capacity left: if we skip node k, we must skip its entire subtree (dp[end[k]][c]), and if we take node k, we unlock its children (fee[k] + dp[k + 1][c - size[k]]), which still runs in exact O(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 parents max(greedy_fee, best_single_tx_fee) guarantees at least 50% of optimal and greedy_fee >= OPT - max_single_tx_fee. Empirically, replay historical mempool snapshots, compute the exact tree-DP optimum at capacity = 100, inspect the distribution and p01/worst-case tail of greedy_fee / optimal_fee, and benchmark wall-clock latency at 10^5–10^6 transactions to prove block-template assembly finishes in milliseconds.

Follow-up questions

Similar questions

More Coinbase interview questions

All 99 Coinbase questions →