Exercise 2: Re-Inserting an Existing Key Updates, Never Duplicates — Possible Solution ==================================================================== THE TEST ------------------------------ root = BTreeNode(leaf=True) for k in range(1, 11): root = btree_insert(root, k, f"original_{k}") before_nodes = count_all_nodes(root) root = btree_insert(root, 5, "UPDATED") after_nodes = count_all_nodes(root) RESULT ------------------------------ before_nodes == after_nodes == 5 btree_search(root, 5) == "UPDATED" The node count is identical before and after the second insert of key 5, and the stored value correctly reflects the newer "UPDATED" value, not the original "original_5". WHY THE NODE COUNT NEVER CHANGES ------------------------------ insert_into_node's own very first check, at every level it visits (leaf or internal), is: if i < len(node.keys) and node.keys[i] == key: node.values[i] = value return None Before ever inserting a NEW entry, the function first checks whether the target key is ALREADY present at the current search position. If it is, the function overwrites the existing value in place and returns None immediately -- signaling "nothing changed structurally, no split needed" all the way back up the call chain. Neither `node.keys.insert(...)` nor `node.children.insert(...)` is ever reached for an already-present key -- no new key is added anywhere, so no node can possibly overflow and split, which is exactly why the total node count stays fixed at 5 (the same tree structure that resulted from the original 10 sequential inserts). WHY THE VALUE REFLECTS THE SECOND INSERT ------------------------------ `node.values[i] = value` is a plain assignment, unconditionally overwriting whatever value was previously stored at that position with whatever value was just passed in -- there's no check anywhere that compares the new value against the old one, or that refuses to overwrite an existing entry. The second call, `btree_insert(root, 5, "UPDATED")`, simply replaces "original_5" with "UPDATED" at the exact same (key, value) slot the first insert created. WHY THIS WORKS AS AN ANSWER ------------------------------ This confirms btree_insert implements real UPSERT semantics (update if present, insert if absent) rather than blind insertion -- a genuine, necessary property for a real index, since a real database table's own UPDATE statement (changing an existing row's value) has to update the matching index entry too, not silently accumulate duplicate entries for the same key every time a row's value changes.