Data Structures & Algorithms practice
Data Structures & Algorithms · Hierarchical Structures

Binary Search Trees: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1The Search Tree PropertyEasyMust Do

A binary search tree (BST) is a binary tree with distinct keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. The rule is about whole subtrees, not just the two children. Trees are built from TreeNode (DSA Topic 13): a val and a left and a right reference, None for no child. from_level(values) builds a tree from a level-order list with None for a missing child, to_level(root) reads it back, and show(root) prints a tree sideways, the root at the left edge. Keys are distinct integers until duplicates come up later in this topic.

Write first_violation(root), a brute-force check of the rule, and run it on the standard example tree T10.

  1. At each node, walk its left subtree to find the largest key and its right subtree to find the smallest, and compare them with the node's key. Count every node the walks visit (that is O(n) per node: O(n^2) on a path, O(n log n) on a balanced tree).
  2. Build T10 from the level-order list [41, 20, 65, 11, 29, 50, 91, None, None, None, 32, None, None, 72, 99] and print it with show.
  3. Run the check on T10 and on two near misses: a tree with a child on the wrong side of its parent, and a tree with a key two levels down on the wrong side of the root. For each, print yes or no and the first offending key.
  4. Count the walk steps on T10 and on a right path of 400 keys ([1, None, 2, None, 3, ...], built by code). Assert the path costs exactly n(n - 1) / 2, and say what that is per key beside T10.
Q2Why In-Order Is SortedEasyMust Do

A binary search tree (BST) is a binary tree with distinct keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. A tree's in-order list is its left subtree, then the node, then its right subtree (DSA Topic 13). A tree shape is the pattern of children with the keys left out: a nested tuple (left_shape, right_shape), with None for the empty tree. shapes(k) returns every shape with k nodes.

  1. Prove in five lines, by induction on the height (each subtree of a BST is itself a BST of smaller height), that the in-order list of a BST is strictly increasing. The empty tree is the base. Print the five lines.
  2. The converse holds too: a tree whose in-order list is strictly increasing is a BST. Check both directions on every labelling of every shape with up to five nodes (5,412 labelled trees; use shapes and in_list from DSA Topic 13 and a brute-force check of the rule at every node). The two tests must agree on every tree, and exactly one labelling of each shape must be a BST (65 in all).
  3. So a shape and a set of keys decide where every key goes. Write build_bst(shape, keys), which makes fresh nodes in the shape and takes keys from an iterator in in-order, so that increasing keys make a BST. Build ALL_BST, every BST on the keys 1..k for k = 0..7, and check that there are 626 of them and that each is a BST with the right in-order.
  4. State the cost: O(n) for in_list, O(k) for build_bst.
Q3Searching A BSTEasyMust Do

A binary search tree (BST) is a binary tree with distinct keys in which every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. Write search(root, x) as a loop. It returns the node holding key x, or None when x is absent, and it changes nothing. TreeNode, from_level and in_list are the DSA Topic 13 helpers (the node class, the builder from a level-order list, and the in-order list). shapes(k) lists every tree shape with k nodes (DSA Topic 13); build_bst(shape, keys), written earlier in this topic, makes fresh nodes in that shape and labels them with the keys in in-order. ALL_BST is every BST on the keys 1..k for k = 0..7 (626 trees), built with them.

  1. Compare x with the node's key: equal means found, smaller means x can only be in the left subtree, larger only in the right. One comparison per level gives O(h) time and O(1) space.
  2. Build T10 from [41, 20, 65, 11, 29, 50, 91, None, None, None, 32, None, None, 72, 99] and trace the search for 32 and for 60, printing each step.
  3. Count the nodes visited for every present key and for every absent key from 0 to 100, in a counted copy, and assert the largest count is at most the height.
  4. Check search against x in in_list(root) on all 626 trees of ALL_BST for every x in 0..k + 1.
  5. DSA Topic 13 had to visit every node to find a value in an unordered tree. Count the visits of both methods on the 429 trees with seven keys, for every x in 0..8, and print the totals.
Q4Recursive SearchEasy

The same search as recursion: return search_rec(node.left, x) when x is smaller. Each call is one frame, so the recursion uses O(h) stack space where the loop used O(1).

  1. Write search_rec(node, x) and a counted copy that passes a depth argument, starting at 1, and returns the frames used.
  2. On T10 (the example tree from [41, 20, 65, 11, 29, 50, 91, None, None, None, 32, None, None, 72, 99]), print the frames used for each key beside the height, and assert the bounds.
  3. Write the broken variant that calls search_rec(node.left, x) without return. Scan ALL_BST (every BST on 1..k, k = 0..7) for the smallest failing tree and print found or not found for its keys beside the truth. Do the same for [2, 1, 3].
  4. Check the fixed version returns the same node as the loop on every tree of ALL_BST for every key.
Q5Inserting A KeyEasyMust Do

A binary search tree (BST) is a binary tree with distinct keys in which every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. A new key goes where an unsuccessful search for it ends: walk down as in a search and hang a new node in the empty child slot where the walk stops, so a new key is always a leaf and nothing else moves.

Write insert(root, x) as a loop. It changes the tree in place and returns the root: a new node when root is None, otherwise the same root. A key already present is left alone (keys are distinct). Write from_keys(keys), which inserts the keys one at a time in the order given, ignores repeats and returns the root. ORDERS is every insertion order of the keys 1..k for k = 0..7, as tuples (5,914 orders).

  1. Trace inserting 32 into the tree built from the other nine keys of T10 = [41, 20, 65, 11, 29, 50, 91, 32, 72, 99] (in that order, without 32), printing each comparison and show() (it prints a tree sideways, the root at the left edge, right children above) before and after.
  2. Check every order in ORDERS: the tree passes a brute-force check of the search-tree rule, its in-order list equals sorted(set(keys)), and inserting every key twice builds the same tree.
  3. Fuzz 300 seeded key lists with repeats (including the empty list, one key and sorted lists), count each of those cases, and catch every exception as a failure.
  4. Show the broken variant that assigns the new node to the local variable node instead of to the parent's reference, so nothing is linked.
Q6Recursive Insert And Re-LinkingEasy

Recursive insert returns the root of the subtree it was given and the caller stores it: node.left = insert_rec(node.left, x). That one pattern handles the empty tree and the new leaf with no special case. The price is that every node on the path is re-linked.

  1. Write insert_rec(node, x), and a counted copy that counts the reference writes per insert and how many of them change the reference.
  2. Insert 32 into the tree of the other nine keys of T10 = [41, 20, 65, 11, 29, 50, 91, 32, 72, 99] and print the writes and the changed writes.
  3. Over every insertion order of 1..k for k = 0..7, check that the counted copy builds the same tree as the loop insert and that each insert changes exactly one reference.
  4. Show the broken variant with no return node at the end: the call that recursed returns None, and the caller stores it. Print its output beside the truth.
  5. Insert a key at the end of a path of 2,000 keys with the recursion and with the loop, and print what happens.
Q7Insertion Order Decides The ShapeEasy

The same keys in another order build another tree.

  1. Insert every order of 1..k for k = 0..7, count the distinct trees (by to_level) and print them beside math.comb(2 * k, k) // (k + 1): every shape is built by some order.
  2. Count the orders that build a path (no node with two children) and compare with 2 ** (k - 1), then check the reason: every key is the smallest or the largest of the keys still to come (itself included). Also print the most orders any single tree gets.
  3. Write random_bst(n, rng, keys), a seeded shuffle of exactly n distinct keys inserted in that order; a wrong count must raise ValueError (show it once). Write path_bst(n, side), linked directly in O(n).
  4. Check path_bst(50) against inserting 1..50 in increasing and in decreasing order.
Q8Minimum And MaximumEasy

The smallest key of a BST is at the end of the left spine: walk left until there is no left child. The largest is at the end of the right spine. The minimum need not be a leaf.

  1. Write minimum(root) and maximum(root); an empty tree raises ValueError. Show that from_keys([5, 2, 3]) has a minimum with a right child.
  2. Count the steps (nodes moved through) on T10, on path_bst(800) both ways and on random_bst(1000).
  3. Check against min and max of in_list on every non-empty tree of ALL_BST and on 200 seeded random trees, counting the empty, single-key and sorted-order cases and catching every exception as a failure.
Q9How Tall Can It BeEasy

A tree of n keys has height (counted in nodes) between ceil(log2(n + 1)) and n.

  1. Argue both bounds in comments: level d holds at most 2^d nodes, and every level holds at least one.
  2. Write height(root) level by level with no recursion, so that it measures any tree, and check it on the empty tree, a single node, every tree of ALL_BST (assert both bounds) and a path of 2,000 keys. Show that a recursive height raises RecursionError on that path.
  3. Over all 5,040 orders of 1..7, print the histogram of heights and the mean. Assert no order beats the lower bound and that only the 2^6 path orders reach 7.
  4. Print how many of the orders give the best height, as a share.
Q10Deleting A LeafEasy

Deleting starts with a search that remembers the parent. A leaf is unlinked by setting the parent's reference on its side to None; a tree that is a single leaf becomes empty, which is why delete returns the root.

  1. Write delete_leaf(root, x) for this case only. It changes the tree in place and returns the root (None when the tree was one leaf). It raises ValueError when x is missing or is not a leaf.
  2. Trace deleting 32 from T10 (the tree of [41, 20, 65, 11, 29, 50, 91, None, None, None, 32, None, None, 72, 99]), with show() before and after.
  3. Check on every leaf of every tree in ALL_BST (each tree built fresh): the in-order list loses exactly x and the search-tree rule holds. Check that the errors are raised for every non-leaf and for missing keys.
  4. Say in a comment what C does with the removed node and what CPython does.
Q11Deleting A Node With One ChildEasy

A binary search tree (BST) is a binary tree with distinct keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. Deleting a key is the first operation that can break that rule, so build it in two steps, the easy cases first.

Write delete_one(root, x). It removes key x in place and returns the root. It handles the two easy cases only:

  • a node with no child (a leaf) is unlinked;
  • a node with one child is spliced out: its parent's reference skips to that child, and the child's whole subtree moves up one level unchanged. It stays on the correct side of every key above it, because it was already on that side of its old parent and its old parent was on that side of everything above. The root with one child is the same splice with no parent: the child becomes the root.

A key that is missing changes nothing (the same root comes back). A node with two children raises ValueError and leaves the tree untouched (the next question's job).

  1. Show the splice on [5, 3, 8, 2, None, None, 9] (level order, None for a missing child): delete 3, then 8, then the root of [5, None, 8, None, 9].
  2. Check it on every key of every BST on the keys 1..k for k = 0 to 7 (626 trees, a fresh copy each time): the in-order list must equal the old one minus x, the brute-force search-tree property (walk the whole left and right subtree of every node) must hold, and a two-child key must raise. Count the leaf, one-child, root-with-one-child, two-child and absent cases and assert each was met.
  3. On path_bst(800) (a right path of 800 keys, written by code) delete the middle key 400 and print the height before and after (height counts nodes).
Q12Deleting A Node With Two ChildrenMediumMust Do

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. The in-order successor of a key is the smallest key larger than it; for a node with two children it is the leftmost node of the right subtree.

Write delete(root, x). It removes key x from the BST in place (the nodes are changed, no new tree is built) and returns the root: the old root, unless the root itself was removed, in which case the new root is its only child, or None when the tree became empty. A key that is missing changes nothing: the same root comes back and no error is raised. A key appears at most once. State the three cases for the node holding x:

  1. No child: unlink it (its parent's reference becomes None).
  2. One child: splice it out (its parent's reference skips to the child, and the child's whole subtree moves up unchanged).
  3. Two children: the successor has no left child (it is the leftmost node of the right subtree, so nothing smaller is below it). Copy its key into the node, then remove the successor node by case 1 or 2. Say why this keeps the rule: the successor is the smallest key larger than the node's, so every key of the left subtree is still smaller than it and every other key of the right subtree is still larger. The predecessor (the rightmost node of the left subtree) works the same way mirrored.

Then show it working.

  1. Trace deleting 41 (the root) and then 20 from the tree built by inserting 41, 20, 65, 11, 29, 50, 91, 32, 72, 99 in that order: print the sideways picture before and after each delete.
  2. Fuzz it: 300 seeded scripts of mixed inserts and deletes, comparing the tree's in-order with a sorted list after every step. Count the empty-tree, single-node, leaf, one-child, two-child, root, absent and sorted-start cases and assert each was met. Any exception counts as a failure.
  3. Check every key of every BST on the keys 1..k for k = 0 to 7 (626 trees, a fresh copy each time) against the sorted list and the brute-force search-tree property.
  4. Broken variant: in case 3 copy the left child's key and remove the left child. Run it on the smallest tree it fails on and print the wrong tree beside the right one.
Q13Deleting By Relinking Nodes, Not Copying KeysMedium

A search tree's delete can move a key between nodes: when a node has two children, the usual version copies the successor's key into it and removes the successor's node. Any reference you kept to a node (a handle a caller holds, a dict from key to node) then points at the wrong thing: the node that held 50 may now hold 65, and the node that held 65 is no longer in the tree.

Write delete_relink(root, x): it deletes key x in place and returns the root, a missing key changes nothing, and a node with two children is handled by moving the successor node itself (the leftmost node of the right subtree) into the deleted node's place: re-link its old parent, give it both of the deleted node's children and put it under the deleted node's parent. Every surviving key stays in the node that always held it.

  1. Show the difference. Build random_bst(300, rng) with a seeded rng, keep a dict from key to node, delete 120 seeded distinct keys, then count the surviving keys whose node is no longer the node the tree reaches for that key, and the deleted keys whose kept node now holds a different key. Print the counts (never a node): positive for the copying delete, 0 for delete_relink.
  2. Check delete_relink with 300 seeded scripts of mixed inserts and deletes against a sorted list (empty tree, single node, sorted start, leaf, one-child, two-child, root and absent cases all counted and asserted), and on every key of every BST on the keys 1..k for k = 0 to 7.
  3. Say when relinking matters (parent references, node handles, nodes that carry extra data) and what it costs: still O(h), a few more assignments.
Q14Validating: Why The Parent Check FailsMediumMust Do

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. Write is_bst(root), which returns True when the tree rooted at root is a BST and False otherwise. Contract: keys are distinct, the bounds are strict (a key equal to a bound fails), the empty tree is valid, it must work on a tree of any depth (no recursion) and it stops at the first violation. Trees are written as level-order lists with None for a missing child, such as [10, 5, 15, None, None, 6, 20].

The tempting check looks only at each node and its two children (left child smaller, right child larger). It is wrong, and the rule is about whole subtrees.

  1. Write that parent-only check (parent_only). Run it on [10, 5, 15, None, None, 6, 20]: it says yes, though 6 sits in 10's right subtree. Print the in-order list [5, 10, 6, 15, 20] that shows the break.
  2. Find the smallest tree it gets wrong by scanning every labelling of every shape with up to 5 nodes (a labelling is any permutation of 1..k on the shape: 5,412 labelled trees in all), in increasing size, and print it with the brute-force answer (at every node compare its key with the largest key of its left subtree and the smallest of its right subtree, walking each subtree). The scan should show that [2, None, 3, 1] is one of the smallest.
  3. The fix passes bounds down: every key must lie strictly between the bounds its ancestors set (the lower bound comes from the nearest ancestor it is to the right of, the upper from the nearest ancestor it is to the left of). Write is_bst with an explicit stack of (node, low, high) triples, then say what each pushed pair means on the trap tree and which key fails with which bounds.
  4. Check is_bst against the brute-force property on all 5,412 labelled trees (equal on every one, 65 of them valid), on every tree of every BST on the keys 1..k for k = 0 to 7 (all True), and on path_bst(10**5) (a right path of 100,000 keys, written by code) without recursion. Count pops and the largest stack on a counted copy: a violation next to the root stops after 2 pops, and on a random tree of 1,000 keys the stack never exceeds the height plus 1.
Q15Validating By In-OrderEasy

A second validator uses a fact about search trees: the in-order walk (left subtree, node, right subtree) of a BST is strictly increasing, and a binary tree of distinct keys whose in-order is strictly increasing is a BST (a violation of the subtree rule would put some key out of order in that walk). So walk in order with an explicit stack and check that each key is greater than the one before, stopping at the first descent. The previous key starts as None (not 0, since 0 may be a real key). This is the in-order walk with a stack from the trees topic, with an early stop.

  1. Write is_bst_inorder(root) and the bounds validator is_bst (pasted).
  2. Broken variant: a student writes >= where it should be >, and the equal key passes. Show [2, 2] (a root and a left child, both 2) accepted by it and rejected by the right one.
  3. Compare the two validators with is_bst on every labelling of every shape with 0 to 5 nodes (5,412 labelled trees): equal on all.
  4. Count the nodes each validator visits before it stops, on 200 seeded random trees of 200 keys where one pair of keys has been swapped. Print the two totals side by side with how many trees each stopped before visiting every node. No timing: counts only, from counted copies checked equal to the plain functions.
Q16The k-th Smallest KeyEasy

In-order visits the keys of a search tree in increasing order, so the k-th key popped by an in-order walk is the k-th smallest: walk with a stack and stop there (the in-order walk with a stack, from the trees topic, with an early stop). k is 1-based (k = 1 is the minimum) and a k outside 1..n raises IndexError. Write kth_smallest(root, k) returning the key.

  1. Count the work on a counted copy: exactly k pops and at most k + h pushes (h the height in nodes), asserted on random_bst(10**4, rng) for k = 1, 100, 5,000 and 10,000. Print the pushes, pops and h.
  2. Check it against indexing a sorted list (keys[k - 1]) on every tree of every BST on the keys 1..k for k = 0 to 7 and every k from 1 to n, and check that k = 0 and k = n + 1 raise IndexError.
  3. State the cost: O(h + k) time and O(h) space, so O(n) for the largest k. Name what replaces it: with stored subtree sizes it becomes O(h), later in this topic, and a sorted list answers keys[k - 1] in O(1).
Q17The k-th Largest KeyEasy

Reverse in-order (right subtree, node, left subtree) visits the keys of a search tree in decreasing order, so the k-th key popped is the k-th largest. Write kth_largest(root, k) with an explicit stack that stops at the k-th pop. k is 1-based (k = 1 is the maximum) and a k outside 1..n raises IndexError. The mirror of the k-th smallest walk: it follows the right spine instead of the left.

  1. Check kth_largest(k) == kth_smallest(n - k + 1) for every k on every tree of every BST on the keys 1..k for k = 0 to 7 (626 trees), and against a sorted list read from the end, with IndexError at 0 and n + 1.
  2. Count pushes and pops (from a counted copy checked equal to the plain one) for the largest key on path_bst(1000) built both ways: a right path (each key the right child of the one before) and a left path. Print both. On the right path the walk pushes 1,000 nodes before the first pop; on the left path it pushes 1.
  3. State O(h + k) time and O(h) space, h the height in nodes.
Q18The In-Order SuccessorMediumMust Do

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. The in-order successor of x is the smallest key in the tree that is greater than x. x need not be in the tree. The answer is None when no key is larger.

Write successor(root, x) returning that key, in O(h) time and O(1) space, with no parent references (h is the height in nodes). Walk down from the root. When x is smaller than the node's key, that key is a candidate and the answer is it or something to its left, so record it and go left. Otherwise (the key is x or smaller) every key in the left subtree and the node itself are too small, so go right. The last candidate recorded is the answer.

  1. Trace it on the tree built by inserting 41, 20, 65, 11, 29, 50, 91, 32, 72, 99 in that order, for x = 41, 32, 99 and 40 (40 is absent): print the nodes visited and the answer. Use a separate tracing copy and check it equals the plain function.
  2. Broken variant: "the successor is the right child". Show it on [1, None, 3, 2] (level order, None for a missing child), where it gives 3 for 1 and the answer is 2, and count how many (tree, x) pairs of every BST on the keys 1..k for k = 0 to 7 it gets wrong.
  3. Check against bisect_right on the sorted keys (the successor on a sorted list: the key at index bisect_right(keys, x), or None past the end) for every x from 0 to k + 1 on every BST of the 626, and for 1,000 seeded queries on a random tree of 10,000 keys drawn from 0..39,999; assert the steps never exceed the height.
Q19The In-Order PredecessorEasy

The mirror image of the successor. The predecessor of x is the largest key smaller than x; x need not be in the tree and the answer is None when no key is smaller. Walk from the root: when the node's key is smaller than x it is a candidate (record it) and the answer is it or something to its right, so go right; otherwise go left. The successor of x (the smallest key greater than x) is written the same way: record the key and go left when x is smaller. Both take O(h) time and O(1) space.

  1. Write predecessor and successor and check predecessor against bisect_left on the sorted keys (the key at index bisect_left(keys, x) - 1, or None at index 0) for every x from 0 to k + 1 on every BST of the keys 1..k for k = 0 to 7.
  2. Check the pair: for every present key except the ends, predecessor(successor(x)) == x and successor(predecessor(x)) == x, with None at the ends.
  3. Walk a whole tree in order by repeated successor calls from the minimum: n calls of O(h) each, O(n h) in all, against O(n) for one in-order walk. Count node visits for both on random_bst(1000) and on path_bst(1000) and print the totals and ratios (counted copies, checked equal to the plain functions).
Q20Floor And CeilingEasy

Floor(x) is the largest key <= x and ceiling(x) is the smallest key >= x; each is None when no key qualifies, and x need not be in the tree. Write floor and ceiling for a BST with one walk each. Record a candidate on the turn that keeps it valid and return at once on equality: for floor, when the node's key is below x it is a candidate and the walk goes right; for ceiling, when the key is above x it is a candidate and the walk goes left. Both are O(h) time and O(1) space.

  1. Broken variant: floor returns the key of the last node the walk visited. Show it on [2] with x = 0, where it gives 2 instead of None, and count the (tree, x) pairs of every BST on the keys 1..k for k = 0 to 7 it gets wrong.
  2. Check both against bisect on the sorted keys (floor is the key at bisect_right(keys, x) - 1, ceiling the key at bisect_left(keys, x), as on a sorted list earlier in the course) for every x from 0 to k + 1 on every BST of the 626, and for 1,000 seeded queries on a random tree of 10,000 keys drawn from 0..39,999. Assert that no query visits more nodes than the height.
Q21Range QueriesMediumMust Do

A binary search tree (BST) here is a binary tree of distinct integer keys in which every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. Its in-order walk (left, node, right) lists the keys in increasing order.

Write range_keys(root, lo, hi). It takes the root of a BST (or None) and returns a new list of every key with lo <= key <= hi, both bounds inclusive, in increasing order. It does not change the tree. When lo > hi, or no key lies in the range, it returns [].

  1. Show the naive way first: list the whole tree in order and filter it. State its cost.
  2. Write the walk that skips what cannot matter: an in-order walk with an explicit stack that does not go left from a key below lo (that key and its whole left subtree are too small), and stops at the first key above hi (everything after it in order is larger).
  3. Write a counted copy range_visits that also returns the number of nodes entered, and assert visits <= k + 2 * h (k keys reported, h the height in nodes) on every range tried. Print visits, k and h for a narrow, a wide and an empty range on a random tree of 10,000 keys.
  4. Check range_keys against a sorted-list filter on every BST with up to 7 keys, for every lo <= hi from 0 to k + 1, and on 300 seeded trees (some empty, some a single node, some built in sorted order), each with 30 seeded ranges.
Q22Average Search CostMedium

A successful search for a key at depth d (root at depth 0) visits d + 1 nodes. So the average cost of finding a key that is present is 1 + (sum of all depths) / n, and one level-order pass can compute it without searching at all.

  1. Write depth_totals(root): one level-order pass that returns n, the sum of node depths, and the same for the empty child slots (an unsuccessful search ends at one of the n + 1 empty slots, having visited the node above it and that node's ancestors: depth + 1 nodes).
  2. Write a counted search search_visits(root, x) and check the formula by searching every key (successful) and one probe per gap between keys, i + 0.5 (unsuccessful).
  3. Print the averages for the balanced tree of 7 keys, a path of 7, a random tree of 1,000 keys and a path of 1,000 (for the path the formula is (n + 1) / 2: assert it). Check the formula on every BST with up to 7 keys.
  4. Measure how close a random tree's average comes to 2 * ln(n).
Q23A Balanced BST From Sorted KeysEasy

Inserting sorted keys one at a time builds a path. If you hold all the keys sorted, you can do far better: take the middle key as the root, build the left subtree from the keys before it and the right subtree from the keys after it, recursively. The height is then the smallest possible, ceil(log2(n + 1)).

  1. Show the slicing version first (keys[:mid], keys[mid + 1:]) and count how many keys it copies.
  2. Write balanced_bst(keys, lo=0, hi=None) with index bounds (the range lo <= i < hi, half-open) so that nothing is copied. Say its time and space.
  3. Check height equals ceil(log2(n + 1)), the in-order list equals the input, and the tree is a BST, for every n up to 600 and for the sizes around each power of two up to 2^15.
  4. Show the bug a student meets with inclusive bounds: the right half starts at mid instead of mid + 1, so a range of two keys calls itself forever. Catch it and print the exception's type.
Q24Memory Per KeyMedium

A key in a tree costs a whole node. Measure how much, and compare with the flat structures Python has instead.

  1. Allocate the keys before tracing, so that only the structure is counted (the keys cost the same in every structure and are left out).
  2. With tracemalloc, build with 100,000 keys: a tree by from_keys (a slotted node with three fields), the same insertion order into a node class that also stores a size, and one that also stores a parent reference, then a sorted list, a dict and a set. Print bytes per key and each structure's ratio to the sorted list.
  3. Check that sys.getsizeof of one slotted node agrees with the measured bytes per node.
  4. State the ratio of the plain tree to the sorted list from the printed numbers.
Q25A BST Is A Sorted List You Can Insert IntoMedium

A sorted list with bisect and a BST answer the same ordered questions. Put them side by side on the same 10,000 seeded keys and count the work, with no timing.

  1. Count search (nodes visited against the binary search's steps), insert (nodes the tree walks and links; for the list the search plus the shifts, where insort at index i moves len(a) - i elements), minimum, the k-th smallest (k = 5,000) and a range of 100 keys (tree visits against two binary searches plus the slice's copy).
  2. Print the table from the computed counts.
  3. Check at the end that the tree and the list hold the same keys.
  4. State the honest caveat: insort moves its elements with one C-level memmove, so counts overstate its cost, and the timing comes later in this topic. Close with what only the tree can promise.
Q26Duplicate Keys: Four PoliciesMedium

The kit's insert ignores a key that is already present. Four ways keep duplicates instead, each with insert, count(x) and delete_one(x) (remove one copy; a missing key changes nothing):

  1. Count field: one node per distinct key, with a count.
  2. Equal goes right: a second x becomes a new node on the right, and count(x) keeps walking right after a match.
  3. Reject: the kit's insert (right for a set); count(x) is 1 or 0 and delete_one removes the key.
  4. Tie-breaker: make keys distinct as (key, seq) tuples (tuples compare element by element), so a multiset becomes a set, and count(x) counts the tuples whose first element is x.

Check each policy against collections.Counter (against a set for the reject policy) on 300 seeded scripts of inserts, counts and delete-ones with keys in 0..9, hitting the empty tree, a single key and a sorted insertion order. Print the nodes each policy uses for 10,000 inserts of keys in 0..99.

Q27Order Statistics With Subtree SizesMediumMust Do

A binary search tree (BST) here is a binary tree of distinct integer keys in which every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. A size tree is a BST whose nodes also store size, the number of nodes in the subtree rooted there, itself included (a leaf has size 1, an empty subtree 0). The stored sizes must stay right as keys arrive.

Write these, each with its contract in the docstring:

  1. SizeNode(val, left=None, right=None) and size_of(node), which is 0 for None.
  2. size_insert(root, x): puts key x in the size tree and returns the root. It changes the tree in place. It searches first, so a key already present changes no size.
  3. select(root, k): the k-th smallest key, 1-based (k = 1 is the minimum). Go left while k <= the left subtree's size; stop when k equals that size plus 1; otherwise subtract that size plus 1 and go right. A k below 1 or above the number of keys raises IndexError.
  4. rank(root, x): how many keys are smaller than x. x need not be in the tree.
  5. sizes_ok(root): True when every stored size is 1 plus the two children's stored sizes.

Show the bug of adding 1 to the sizes on the way down before checking whether the key is present: inserting 2, 1, 2 leaves the root's size at 3, not 2. Check 400 seeded scripts of inserts (repeats included) against a sorted list: select(root, k) == a[k - 1] for every k, rank == bisect_left, sizes_ok after every insert, the IndexError contract, and cover the empty tree, a single key and sorted insertion orders. Then count the steps of select against the in-order walk that pops k nodes, on a random tree of 10,000 keys.

Q28Rank And Range CountsMedium

How many keys lie in [lo, hi] (both bounds inclusive)? On a size tree (a BST whose nodes store their subtree sizes, built earlier in this topic) the answer takes two O(h) walks however many keys are counted: the keys <= hi minus the keys < lo.

  1. Write rank_le(root, x), a walk like rank that also counts a key equal to x, and count_range(root, lo, hi) (0 when lo > hi).
  2. Write counted copies and print node visits for count_range and for listing the range with the pruned in-order walk, for ranges holding 10, 1,000 and all 10,000 keys of a random size tree. Assert each count walk visits at most h nodes and the listing at most k + 2h.
  3. Check the count against bisect_right(a, hi) - bisect_left(a, lo) on size trees built from every tree of ALL_BST (its pre-order fed to size_insert, so the same shape), for every lo <= hi from 0 to k + 1, and on 300 seeded trees, sorted orders included, each with 40 seeded ranges.
Q29Lowest Common Ancestor In A BSTEasy

In a binary tree the lowest common ancestor (LCA) of two nodes is the deepest node that has both in its subtree (a node counts as its own ancestor). A general tree has no order to help, so the lowest common ancestor there searches both subtrees: O(n) (DSA Topic 13 built that one). A search tree gives the answer directly: the LCA of present keys p and q is the first node on the path from the root whose key lies between them, inclusive.

  1. Write lca_bst(root, p, q): while both keys are smaller than the node, go left; while both are larger, go right; otherwise stop. O(h) time, O(1) space, no recursion and no parent references. Both keys are assumed to be in the tree, in either order.
  2. Show the bug of assuming p < q: on the tree [1, None, 2] with p = 2 and q = 1 it returns None. The fix orders the pair first.
  3. Check against the deepest common key of the two root-to-key paths for every ordered pair of keys of every BST with up to 7 keys.
  4. Count nodes visited by the general search and by lca_bst on a random tree of 10,000 keys, and on a path of 100,000.
Q30Successor With Parent PointersHard

A successor of a node is the node with the next larger key. If every node also stores a parent reference, the successor needs no stack and no search from the root:

  • if the node has a right child, the successor is the leftmost node of its right subtree;
  • otherwise climb while the node is its parent's right child; the parent above that climb is the successor, and there is none (None) at the maximum.
  1. Write PNode (val, left, right, parent), pinsert(root, x) that sets the parent, successor(node), and a counted copy. A step is one reference followed, including the last step up to None.
  2. One call can cost O(h): count the worst single call (about n steps on a path). But a walk over the whole tree costs O(n): each edge is crossed at most once down and once up. Measure total steps for a random tree and both paths of 1,000 keys, and assert total steps <= 2n - 1.
  3. Show the bug of returning node.parent without checking which side the node came from: on the tree [1, None, 2] it gives 1 as the successor of 2.
  4. Check every node of every insertion order of up to 7 keys, and 300 seeded random trees, against a sorted list.
Q31A Lazy Range IteratorMedium

A generator that yields the keys of a search tree in [lo, hi] in increasing order, lazily: asking for the first five keys must not walk the whole range. This is DSA Topic 13's in-order iterator (cited), with two changes that only the search-tree order allows: it starts in the middle of the tree, and it stops early.

  1. Write range_iter(root, lo, hi). It first walks towards lo, pushing only nodes with key >= lo (a node below lo is skipped together with its whole left subtree). Each step then pops one node, yields it unless it is above hi (then it stops, because every later key is larger), and pushes the left spine of its right child.
  2. Write a counted copy that records the nodes touched (looked at or pushed) and the stack's peak. On random_bst(10**5) take the first 5 keys with itertools.islice, and print the nodes touched against the height and against the n nodes the naive in_list filter walks. Assert touched <= 2 * h + 5 and peak <= h.
  3. Check the generator against a sorted-list slice for every lo and hi on every tree of ALL_BST, and on 1,000 seeded ranges that include the empty tree, a single node and a sorted insertion order. Count each edge case hit and treat any exception as a failure.
Q32Two Sum In A BSTMedium

Is there a pair of distinct keys in a search tree whose sum is target? A key cannot pair with itself.

  1. Write two_sum_set(root, target): walk the tree and keep a set of the keys seen so far (DSA Topic 7's two-sum with a map, cited). It returns (found, keys_held).
  2. Write two_sum_bst(root, target) with two stack iterators: one ascending from the minimum and one descending from the maximum. Move them like DSA Topic 4's two pointers on a sorted list (cited): a sum that is too small advances the ascending one, a sum that is too large advances the descending one, and they stop when they meet. It returns (found, keys_held) where keys_held is the two stacks' peak sizes added.
  3. Check both against a brute force over all pairs, for every target in 0..2k + 2 on every tree of ALL_BST, and on 200 seeded trees that include the empty tree, a single node and a sorted insertion order (count each).
  4. On random_bst(10**4) with a target no pair reaches, print the keys held by each method and the height, and assert the iterators hold at most h nodes each.
Q33The Closest KeyEasy

Find the key nearest to x (x need not be in the tree; it may be a half-integer). When two keys are equally near, the smaller key wins. An empty tree gives None.

  1. Write closest(root, x): one walk down the search path for x. Every node on that path is a candidate (the largest key <= x and the smallest key >= x are both on it, because the walk turns right after a key below x and left after a key above it), and the best is kept by comparing the tuples (abs(key - x), key).
  2. Write the broken variant that keeps whichever equally near candidate came first. Scan every tree of ALL_BST and every half-integer x for the smallest tree where it is wrong, and print its output beside the truth. Do the same on the tree [4, 2] with x = 3.
  3. Check the good version against DSA Topic 3's closest element with bisect (cited) for every integer and half-integer x from -1 to k + 2 on every tree of ALL_BST, and on 1,000 seeded queries that include the empty tree, a single node and a sorted insertion order. Count the ties.
Q34Trimming To A RangeMedium

Remove every key outside [lo, hi] from a search tree, in place, and return the new root (inclusive bounds; the result may be empty).

  1. Write trim(node, lo, hi) recursively. A node below lo is replaced by its trimmed right subtree (everything on its left is smaller still), a node above hi by its trimmed left subtree, and a node in range keeps both sides, trimmed. A dropped subtree is dropped whole: in C each removed node would be freed, and CPython frees a subtree when its last reference goes.
  2. Write the broken variant that returns node.right (or node.left) without trimming it. Scan the trees with 0 to 7 keys for the smallest failing case and print its wrong output beside the truth, then do the same for [1, None, 2, None, 3] trimmed to [2, 2].
  3. Check trim for every lo <= hi on every BST with 0 to 7 keys (rebuilt fresh each time) against the filtered in-order list, with property_holds and is_bst as the checks that the result is a search tree. Count the visits on random_bst(10**4) and assert visits <= kept + 2 * h.
  4. Show the recursion depth: a path of 800 keys is fine; a path of 2,000 raises RecursionError.
Q35Rebuilding A BST From Its Pre-OrderHard

A search tree's in-order is its sorted keys, so its pre-order alone fixes the tree. (DSA Topic 13 needed a pre-order and an in-order for a general tree: cited.)

  1. Write the naive rebuild: the first key is the root, the following keys smaller than it form the left subtree, and the rest the right subtree. Find the split by scanning, and count the key comparisons on a path of 800 keys and on a random tree of 800.
  2. Write the better rebuild: pass an upper bound down and take keys from one shared index while they fit. Count the key tests and assert they are 2n + 1 (each key is read once).
  3. That recursion is as deep as the tree, so write an iterative version with a stack too, and rebuild path_bst(10**5) (both sides) with it. Show that the recursive one raises RecursionError on a path of 2,000.
  4. Check to_level(rebuild(pre_order)) == to_level(root) for every tree of ALL_BST, for 300 seeded trees and for the paths, with all three versions.
Q36Serialising A BST CompactlyEasy

DSA Topic 13 wrote a tree down with a marker for each missing child: 2n + 1 tokens for n nodes (cited). A search tree needs only its n keys in pre-order, because the bound-passing rebuild recovers the tree: a key that fits under the current bound is the next node, and anything bigger ends the subtree.

  1. Write to_markers(root) (pre-order, "#" for each missing child) and to_compact(root) (the pre-order keys only), and from_compact(keys) (the bounds rebuild). Print the token counts of both on T10 (the tree from inserting [41, 20, 65, 11, 29, 50, 91, 32, 72, 99]) and on random_bst(1000), and assert 2n + 1 and n.
  2. Check the compact round trip on every tree of ALL_BST. Also check that inserting the pre-order keys into an empty tree one by one rebuilds the tree (every key arrives after all its ancestors), and so does inserting the level-order keys. Count the ancestors visited by the inserting rebuild on random_bst(1000) against the bounds rebuild.
  3. Show that the in-order is not enough: group ALL_BST by in-order and print how many trees share one.
  4. Show that the compact form is for search trees only: a tree that is not one does not survive it.
Q37Checking A Pre-Order SequenceHard

Is a sequence of distinct keys the pre-order of some search tree? Keep a stack of the keys whose right subtree has not started, and a lower bound. A key larger than the stack's top pops it and raises the bound to it, because that key's right subtree has begun. Any later key below the bound is impossible. This is DSA Topic 10's monotonic stack (the next greater element, cited).

  1. Write is_preorder(seq) and argue in a comment why the bound is right: a key after an ancestor's right subtree began must lie inside that subtree, so it is larger than that ancestor.
  2. Check it against an oracle: insert the sequence in order and compare that tree's pre-order with the sequence (valid exactly when they are equal), on every permutation of 1..k for k <= 7. Print how many are valid for each k and assert the counts equal the Catalan numbers from math.comb.
  3. Fuzz on 300 seeded sequences, valid and shuffled, with the empty sequence, a single key and a sorted one counted. Treat any exception as a failure.
  4. Write a counted copy that also returns the stack's peak, and assert the peak is at most the height of the tree the sequence builds.
Q38A BST To A Sorted Doubly Linked List And BackMedium

Turn a search tree into a sorted doubly linked list in place, with no new nodes: each node's left becomes prev and its right becomes next (DSA Topic 12's doubly linked list, cited). Then turn the list back into a balanced tree, again with no new nodes.

  1. Write to_dll(root): one in-order walk with a stack, linking each node to the one before. Read a node's right child before overwriting it. Return the head (or None).
  2. Write from_dll(head): count the list, then build in in-order, taking the next list node as each subtree's root comes up. Each subtree gets about half the remaining nodes, so the recursion is O(log n) deep.
  3. Check on every tree of ALL_BST and on path_bst(10**4) both ways: the set of node ids is unchanged (compared, never printed), the in-order keys are preserved, prev and next agree in both directions, and the height comes back as ceil(log2(n + 1)).
Q39Merging Two BSTsMedium

Two search trees of m and n keys become one new tree, and the inputs stay as they are. A key that is in both trees appears once.

  1. Write the naive merge: insert one tree's keys, in its pre-order, into the other, with a counted insert. Build A from keys 0..999 in random order and B from keys 1000..1999 in random order, so every key of B is above every key of A. Print the comparison count and the height of the result.
  2. Write the linear merge: the in-order lists of both trees, merged as sorted lists (DSA Topic 9's and DSA Topic 12's merge, cited), then balanced_bst. Count the comparisons and print the height; assert at most m + n - 1 comparisons and the height ceil(log2(size + 1)).
  3. Check against sorted(set(a + b)) on 200 seeded pairs (sizes 0 to 60, overlapping keys) and on pairs from ALL_BST with shifted keys, with the empty tree, a single node and a sorted insertion order counted. Check that the inputs are unchanged.
Q40The Greater-Sum TreeEasy

Replace every key of a search tree with the sum of all keys greater than or equal to it, in place.

  1. Write greater_sum(root): a reverse in-order walk (right, node, left) with a stack, carrying a running total. It changes the tree in place and returns the root.
  2. Check it against suffix sums of the sorted keys on every tree of ALL_BST (rebuilt fresh each time) and on random_bst(10**4) with keys shifted to be positive. Print a five-key tree with show before and after.
  3. With positive keys the result is no longer a search tree, since the keys now decrease from left to right. Check that is_bst is False exactly when n >= 2, that the brute-force property_holds agrees, and that the mirror image (every pair of children swapped) is a search tree again. Show that with negative keys the order can survive.
Q41The Smallest Gap Between KeysEasy

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. Its in-order walk (left subtree, node, right subtree) therefore lists the keys in increasing order, so two keys that are closest in value are always neighbours in that walk.

Write gaps(root) returning ((gap, a, b), (gap, a, b)): the smallest and the largest difference between two neighbouring keys (no key lies strictly between them), each with the pair a < b that achieves it. (The largest difference between any two keys is just the maximum minus the minimum, so the interesting one is the biggest hole.) A tie goes to the pair with the smaller keys. Fewer than two keys gives None. Height h counts nodes: about log2(n) balanced, about 2.5 * log2(n) for a random insertion order, n for a path.

  1. Write the naive version first: for every key, scan all the other keys for the smallest one above it (its neighbour), and keep the best pairs. State its cost and count the comparisons for 1,000 keys.
  2. Write the one-walk version: an iterative in-order walk that keeps the previous key and compares each key with it. State the cost.
  3. Check both on every BST on the keys 1..k for k = 0 to 7 (626 trees), on 200 seeded trees of 0 to 40 random keys, and on a tree built from sorted keys. Count the empty trees, the single-key trees and the sorted-order trees you hit, and treat any exception as a failure.
  4. Print the tie rule at work on a tree whose gaps are all equal, and say what a plain list would need first (DSA Topic 9: sort it; the tree is already in order).
Q42Left And Right RotationsMediumMust Do

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. Its in-order list (left subtree, node, right subtree) is therefore sorted. A rotation is a small change that moves one node up and a neighbour down while keeping the in-order list and the search-tree rule intact.

Rotating the subtree rooted at x left needs x.right to exist. That child y becomes the subtree's new root, x becomes y's left child, and y's old left subtree (the keys between x and y) becomes x's right subtree. Rotating right is the mirror image and needs y.left. Write rotate_left(x) and rotate_right(y): each changes three references in place, creates no node, and returns the new root of that subtree. The caller must store the returned node in the old parent's link (or use it as the tree's root), because the parent still points at the old top. Both take O(1) time and space.

  1. Build the tree by inserting 41, 20, 65, 11, 29, 50, 91, 32, 72, 99 in that order. Print it with show() (a sideways picture: root at the left edge, right children above), rotate left at 65 (the root's right child), store the result, and print it again.
  2. On every BST on the keys 1..k for k = 0 to 7 (626 trees), rotate left at every node that has a right child and right at every node that has a left child, each on a fresh copy. Check the in-order list is unchanged, is_bst (the search-tree check: every key lies strictly between the bounds its ancestors set) still holds, and the opposite rotation restores to_level (the level-order list with None for each missing child). Count the cases, and print how the height of the rotated subtree changes.
  3. Broken variant: call rotate_left and ignore the result. Show it on the level-order list [1, None, 2, None, 3] rotated at key 2, beside the correct code.
Q43Sorted Inserts Make A PathMediumMust Do

A binary search tree (BST) holds distinct integer keys so that, at every node, every key in the left subtree is smaller and every key in the right subtree is larger. Inserting a key walks down from the root: at each node it compares the key with the node's key and goes left if smaller or right if larger, until it reaches a missing child and hangs the new node there. Height counts nodes (one node has height 1). One comparison is counted per node visited on the way down, so a key whose new node ends at depth d (edges from the root) costs d comparisons.

Insert 1, 2, 3, ..., n in increasing order. Every key is larger than all those before it, so it goes right at every node: the tree is a path of height n, a linked list with extra steps. Real data often arrives like this: timestamps, increasing ids, a file that is already in order.

  1. Write a counted copy of insert and count the comparisons for the keys 1..n inserted in order, for n = 10, 100 and 1,000. (from_keys builds a BST by inserting the keys in the order given.) Assert the total is n(n - 1) / 2, and that the counted tree equals the plain one.
  2. Time from_keys on sorted keys and on shuffled keys at n = 500, 1,000 and 2,000 (best of three) and print the time ratio for each n, the ratio only, since it moves with machine load. Count the comparisons of both builds too: the count ratio decides whether the gap grows with n, because the sorted build is O(n^2) and the shuffled one O(n log n).
  3. A recursive search for the largest key of the 2,000-key path raises RecursionError against Python's recursion limit. Catch it, print the error type, and print the height against sys.getrecursionlimit(). The loop version works.
Q44How Tall Is A Random BSTMedium

A binary search tree built by inserting keys in a random order is neither a path nor perfectly balanced. Height counts nodes (one node is height 1); depth counts edges from the root (the root has depth 0); a successful search for a key at depth d makes d + 1 comparisons.

  1. Build trees by inserting keys in a seeded random order and measure the height: seeds 0 to 9 at 1,000 and 10,000 keys, and seeds 0 to 2 at 100,000. Print the range beside log2(n) and the ratio, and the average comparisons per successful search beside 2 ln(n). (DSA Topic 13 measured random tree shapes, a different random model: this is a random insertion order.)
  2. Deleting keys does not keep a tree random. At n = 128 do 10,000 rounds of deleting a random key and inserting a fresh random key, once always taking the in-order successor for a node with two children and once alternating successor and predecessor. Print the average depth before and after, and against a fresh random tree, and say from the numbers whether the tree drifted far.
Q45Nearly Sorted Is Nearly As BadHard

Sorted input builds a path. Input that is only nearly sorted is common: logs merged from a few sources, ids that arrive a little out of order. Build such an order by sorting the keys 0..n-1 by i + rng.random() * d, which moves each key about d places at most (rng = random.Random(4)), and insert the keys in that order. Height counts nodes. A key is a new maximum when it is larger than every key inserted before it (the first key counts).

  1. Measure the height for n = 2,000 with d = 1, 5, 10 and 50, and for n = 4,000 with d = 10. Use iterative code only: recursion would fail on the deepest of these trees. Print each height against the recursion limit as a boolean.
  2. Explain why the right spine of the tree (the root, then right children all the way down) is exactly the new maxima, so the height is at least their number. Count them and print the count beside the height and the fraction of keys that are new maxima.
  3. Print the two fixes: shuffle the keys first, or sort them and build a balanced tree.
Q46The AVL InvariantMediumMust Do

A binary search tree (BST) holds distinct integer keys so that, at every node, every key in the left subtree is smaller and every key in the right subtree is larger. Height counts nodes: the empty tree has height 0 and one node has height 1. A tree is AVL-balanced when, at every node, the heights of its two subtrees differ by at most 1: the balance factor (left height minus right height) is -1, 0 or 1. The invariant keeps a tree's height close to log2(n).

Write check_avl(root) for trees of TreeNode (a value and two child references). It returns the tree's height, recomputing every height in one post-order pass (it never trusts a stored height), and raises ValueError naming the first node that breaks the search-tree order or the balance: the level-order list [2, 1, 3] gives 2, [3, 2, None, 1] raises "balance factor 2 at 3", and [5, 3, 8, 2, 4, 7, 9, 1] gives 4.

  1. Run the three examples and a tree with its order broken.
  2. Why the height is bounded: the fewest nodes in an AVL tree of height h is N(h) = N(h - 1) + N(h - 2) + 1 (a root over the sparsest trees of heights h - 1 and h - 2), which grows like the Fibonacci numbers. Build these sparsest trees for h = 1 to 20, check each with check_avl, and print h beside 1.4405 * log2(n + 2) - 0.3277. Work out the tallest AVL tree that 100,000 keys can make.
  3. Check check_avl against an independent test (every labelling of every tree shape with up to 5 nodes, 5,412 trees, plus 200 seeded random trees and paths) that recomputes the heights node by node with a separate walk. No AVL insert is written here: keeping the invariant on every insert takes rotations, and libraries do that.
Q47The Red-Black RulesMedium

A red-black tree is a binary search tree whose nodes are coloured red or black so that three rules hold: the root is black; no red node has a red child; and every path from a node down to a missing child passes the same number of black nodes (a missing child counts as black). That number is the black height.

  1. Write RBNode (a key, a colour, two children), rb_from_level (a level-order list with None gaps plus the set of red keys) and check_rb, which returns the black height or raises ValueError naming the first broken rule: a red root, a red node with a red child, two different black counts below a node, or a broken search-tree order.
  2. Show one valid tree, [7, 3, 18, None, None, 10, 22, 8, 11, None, 26] with 18, 8, 11 and 26 red, and one failing tree for each rule.
  3. Why the height is at most 2 * log2(n + 1): a subtree of black height b holds at least 2^b - 1 nodes (take away the red nodes and what is left is full to depth b), and no path has two reds in a row, so a path has at most twice as many nodes as black ones. Assert both facts on every tree that passes. Java's TreeMap and C++'s std::map are red-black trees; no insert and no recolouring is written here.
Q48Which Shapes Can Be Red-BlackHard

Red-black rules (the root is black; no red node has a red child; every path down to a missing child has the same number of black nodes) cannot colour every shape. Height counts nodes.

  1. For every binary tree shape with 1 to 7 nodes, try every colouring (itertools.product, 64,978 colourings in all) with the rule checker and count the shapes with at least one valid colouring. Check that every AVL-balanced shape (two subtree heights differ by at most 1 at every node) can be coloured, and print the tallest colourable shape for each size beside 2 * log2(n + 1).
  2. Build very tall red-black trees: for black height b >= 1, the tallest has a black root whose left child is red; that red node's left subtree is the tallest tree of black height b - 1, and its right subtree and the root's right subtree are all-black perfect trees of black height b - 1 (height 2b, 2^(b + 1) - 2 nodes). A black root over the tallest tree of black height b - 1 on the left and a perfect tree on the right gives height 2b - 1 with 3 * 2^(b - 1) - 2 nodes. Number the keys in order, check them with check_rb up to height 32, and conclude what 100,000 keys can make.
Q49BST Or Hash MapMediumMust Do

A binary search tree (BST) stores distinct integer keys so that, at every node, every key in the left subtree is smaller and every key in the right subtree is larger; a search walks one path of h nodes, O(h), with h about 2.5 * log2(n) for keys inserted in a random order. A dict (a hash table, DSA Topic 7) promises O(1) on average for "is this key here, and what is its value", and promises nothing about order. bisect_right(a, x) on a sorted list a returns the index just after any keys equal to x, so a[:i] holds the keys <= x. The floor of x is the largest key that is at most x, or None when there is none.

Python has no search tree type, so you choose between these. Measure each, using timing code that does nothing but the work (best of three, no counters).

  1. Time 100,000 lookups of present keys in a random 100,000-key tree against a dict and a set. Print each time and the ratio, and give a verdict only if the ratio is at least 2.
  2. Time floor queries at 10,000 keys: 1,000 on the tree (walk down, keeping the last key that was at most x) and 100 on the dict (scan every key). Compare the time per query. Check that both give the same answers as a sorted list with bisect_right.
  3. Close with a sentence built from the two verdicts: a dict answers exact lookups; only an ordered structure answers nearest-key questions in O(h).
Q50bisect: The Flat AlternativeMediumMust Do

A sorted list with the bisect module answers everything a search tree answers. bisect_right(a, x) returns the index where x would go in the sorted list a (after any equal keys) by binary search in O(log n); insort(a, x) finds that index and inserts there, and inserting into the middle of a Python list shifts every later element, O(n), but with one fast C memory move. A binary search tree (BST) keeps distinct integer keys so that every key in a node's left subtree is smaller and every key in its right subtree larger; inserting into one costs O(h).

Measure what each costs (best of three, timing code that does nothing but the work; Python has no search tree type, so this is the real choice).

  1. Build a set of n random keys by insort and by inserting into a tree at n = 10,000, 30,000 and 60,000. Print insort time / tree time, the ratio only: no verdict, because the rows sit near the 2x bar. (A verdict anywhere needs a ratio of at least 2; below that, print the ratio only.) In the O lines, h is the tree's height: about 2.5 * log2(n) for random keys, n for sorted ones.
  2. insort's worst case: descending keys go in at the front and shift the whole list every time. Time descending against ascending at 30,000 keys. The tree's worst case is sorted input in either direction: print the height for 1,000 keys each way.
  3. Time floor queries on the tree and on the list, and a set built once with sorted() against the tree, and the memory per key of each.
  4. Close from the computed verdicts on when the sorted list is the better default.
Q51Splitting And JoiningHard

A search tree can be cut in two along a key and glued back together, each in one walk down a single path. split(root, x) returns two search trees: the keys below x, and the keys at or above x. join(a, b) glues two search trees into one when every key of a is below every key of b. Neither copies a node: both only re-link the nodes they are given.

  1. Write split(root, x) with a loop, no recursion and no stack. Collect the low side and the high side with two dummy heads (DSA Topic 12): a node below x keeps its left subtree and goes onto the low side, then the walk continues into its right subtree; a node at or above x keeps its right subtree and goes onto the high side, then the walk continues into its left subtree. It changes the tree in place, creates no node, and the old root must not be used afterwards. x need not be present.
  2. Write join(a, b): take the largest key's node out of a, and make it the root over the rest of a and over b. State its time.
  3. Show T10 (the ten-key example tree) split at 45 with show(), then joined back.
  4. Check on every BST with up to seven keys, for every x from 0 to k + 1: both parts are search trees, the keys of the two parts are the original keys partitioned at x, neither part is taller than the original, and the two parts hold exactly the original nodes (compare the sets of id() values: compared, never printed). Then check split-then-join restores the in-order list on 300 seeded trees, covering the empty tree, one node and sorted insertion order.
  5. Count the nodes split visits in a separate counted copy, and assert it never exceeds the height, on a random tree of 1,000 keys and on a path of 100,000.
  6. Say in one line why keeping the parts balanced needs more than this topic builds.
Q52Root Insertion With RotationsMedium

An ordinary insert puts a new key at a leaf, so the newest key is the deepest one. Root insertion does the opposite: the new key ends up at the root, which makes the most recently inserted keys the fastest to find.

  1. Write root_insert(root, x): if x is already present, return the tree unchanged; otherwise insert x into the correct subtree recursively, which brings it to that subtree's root, then lift it over the current node with one rotation (rotate_right when it came up on the left, rotate_left when on the right). Return the new root. State its time and space with h named.
  2. Check on every insertion order of up to seven keys (5,914 orders): the result is a search tree (by is_bst and by the brute-force property check), the in-order list is the sorted keys, and the last key inserted is the root.
  3. Show the shapes: keys 1 to 500 inserted in increasing order give a left path of height 500 with 500 at the root, and then a key below them all costs a walk of the whole path. Keys 1 to 1,000 in a random order give about the usual random height.
  4. Measure the claim "recent keys are fastest": on 1,000 random keys, count the comparisons to search for each of the 10 newest keys, in a tree built by root insertion and in one built by ordinary inserts. Build the closing sentence from those numbers.
  5. Name what does this for every key a search touches (a splay tree), and what Python code would use for "recently used first".
Q53Rebalancing By RebuildingMediumMust Do

A binary search tree keeps every key of a node's left subtree below the node's key and every key of its right subtree above it, so its in-order list (left subtree, node, right subtree) is the keys in increasing order. A tree's height is counted in nodes: the empty tree is 0 and one node is 1. Inserting keys in sorted order builds a tree as tall as it has keys, and one tall tree can be repaired by rebuilding it: list its keys in order with one walk, then build a balanced tree from that list, the middle key as the root and the same idea recursively on each side.

  1. Write rebalance(root). Its contract: it returns the root of a new search tree of fresh nodes holding exactly the keys of the tree at root, of height ceil(log2(n + 1)) for n keys (the smallest height possible); the old tree is left exactly as it was; the empty tree gives None. State its time and its extra memory.
  2. On a path of 2,000 keys (each key the right child of the one before) print the height before and after. Then count the comparisons of 2,000 searches (one search for every key, one comparison per node visited) before and after, and count the work of the rebuild in node touches (nodes popped by the walk plus nodes created). Keep the counters in separate counted copies and check each copy gives the same tree as the plain code.
  3. From those printed counts, compute after how many searches the rebuild has paid for itself, counting one node touch as one comparison (say so in the output).
  4. Check, on every search tree of up to seven keys and on 100 seeded trees (including the empty tree, one node and sorted insertion order): the in-order list is unchanged, the result is a search tree, its height is ceil(log2(n + 1)), no node is shared with the old tree and the old tree is unchanged.
  5. Say that nothing here rebalances by itself: the program decides when to call rebalance. Libraries that rebalance inside every insert are named.
Q54Rebalancing In Place: Day-Stout-WarrenHard

Rebuilding from a list needs a second copy of every key and every node. Day-Stout-Warren (DSW) rebalances a search tree in place, with rotations only and no list. Like the rebuild, the program calls it explicitly: nothing balances itself.

  1. Write tree_to_vine(pseudo). A dummy node pseudo sits above the root (pseudo.right is the root), so that every rotation is a re-link into a parent. Walk down the right side: at a node with a left child, rotate right (the left child comes up); at a node without one, step to its right child. When the walk ends the tree is one right path, the "vine". Return the number of nodes n.
  2. Write compress(pseudo, count): starting at the dummy, left-rotate count nodes on the vine, every second one, re-linking each into its parent.
  3. Write vine_to_tree(pseudo, n): first compress n - m times, where m = 2^k - 1 is the largest perfect size not above n; then keep halving m and compressing m times, until m is 1. Put the three together as dsw(root): returns the new root, changes the tree in place, creates no node.
  4. Check on every BST with up to seven keys and on 200 seeded trees (the empty tree, one node, left and right paths and random orders): the in-order list is unchanged, the nodes are the same nodes, the result is a search tree of height ceil(log2(n + 1)), and the rotations are at most 2n. Count the rotations in a separate counted copy and print them for a random tree, a right path and a left path of 1,000 keys.
  5. At 100,000 keys compare the peak extra memory (tracemalloc) of DSW and of rebuilding from the in-order list, and time them (ratio only).
Q55One AVL Fix, By HandHardMust Do

An AVL tree is a binary search tree in which, at every node, the heights of the left and right subtrees differ by at most 1. Heights count nodes (the empty tree is 0, one node is 1), and a node's balance factor is the height of its left subtree minus the height of its right subtree, so an AVL tree has every balance factor in -1, 0 or 1. A rotation re-links a node with one of its children without changing the in-order list: rotate_left(x) brings x's right child up over x, rotate_right(y) brings y's left child up over y, and each returns the new top of that subtree, which the caller must store back into the parent (or keep as the root). An AVL tree repairs itself after an insert with at most two rotations; this question does one such repair by hand, on a tree you are given, and does not build an AVL insert.

  1. Build from_keys([50, 30, 70, 20, 40]) (from_keys(keys) inserts the keys in that order into an empty tree with the plain, non-balancing insert; show() returns a sideways text drawing of a tree, the root at the left edge) and show that check_avl accepts it (it returns the height, 3). check_avl(root) returns the height of an AVL tree and raises ValueError, naming the node, if the search order breaks or any balance factor is beyond 1.
  2. Insert 45 with the plain insert and show check_avl raising: the balance factor at 50 is 2, because 50's left subtree is now 3 tall and its right subtree 1, and the extra height went left (to 30) and then right (to 40). That is the left-right case.
  3. Fix it by hand, printing show() after each step: rotate 30 left so 40 comes up, then rotate 50 right and make the result the root. Print the level-order list ([40, 30, 50, 20, None, 45, 70]), the height from check_avl (3), and check the in-order list is unchanged. Also show that rotating 50 right alone is not enough.
  4. State the four cases in a short table (left-left: one right rotation; right-right: one left rotation; left-right: left, then right; right-left: right, then left), and fix one given three-key tree for each, checking the balance factors before and after.
  5. Say what a full AVL insert adds: it repeats this check on the way back up after every insert. It is named here, not written.
Q56Balanced Search Trees ComparedMediumMust Do

A search tree is only as fast as it is short. Height counts nodes (the empty tree is 0, one node is 1), and one search costs at most the height. Three kinds of tree are compared by the tallest they can be with n keys:

  • A perfect (best possible) tree has height ceil(log2(n + 1)).
  • An AVL tree keeps every node's left and right subtree heights within 1 of each other. The fewest nodes an AVL tree of height h can have is N(h) = N(h - 1) + N(h - 2) + 1, with N(0) = 0 and N(1) = 1; the tallest AVL tree with n keys is the largest h with N(h) <= n.
  • A red-black tree colours each node red or black so that the root is black, no red node has a red child, and every path from the root to a missing child has the same number of black nodes. The fewest nodes a red-black tree of height h can have is 3 * 2^(b - 1) - 2 when h = 2b - 1 and 2^(b + 1) - 2 when h = 2b; the tallest has the largest h that fits in n keys.
  1. Write tallest_avl(n) and tallest_rb(n) from those formulas, using two running numbers and no table. Print, for n = 10^3, 10^5 and 10^6, the perfect, AVL and red-black heights, and assert the bounds tallest_avl(n) <= 1.4405 * log2(n + 2) - 0.3277 and tallest_rb(n) <= 2 * log2(n + 1).
  2. Check the formulas against the checkers: build the red-black tree with the fewest nodes for the tallest height at 10^3 and 10^5 keys and test it with check_rb(root) (returns the black height of a red-black tree, raises ValueError if the order, the root colour, the no-red-child rule or the black counts break). The AVL formula comes from induction: the sparsest AVL tree of height h is a root over the sparsest trees of heights h - 1 and h - 2, so N(h) = N(h - 1) + N(h - 2) + 1.
  3. Measure plain, unbalanced trees: random insertion orders at 10^3 keys (seeds 0 to 9) and at 10^5 keys (seeds 0 to 2), and sorted insertion order. Count how many are taller than the tallest red-black tree.
  4. Print one table of all of it and build the closing line from the printed numbers.
  5. Say who uses which tree, and what Python offers: Java's TreeMap and C++'s std::map are red-black, AVL trees are stricter, databases and file systems use B-trees, and Python has no built-in search tree.
Q57The Rank Of Each ArrivalHard

Distinct numbers arrive one at a time. After each arrival, report how many earlier numbers are smaller, before the next number is seen (the rank of the new number among those so far). DSA Topic 9 counted smaller items to the right offline with merge sort, which needs the whole input first; this is the online version.

  1. Write ranks_tree(values) with a size tree: for each value call rank and then size_insert (stored subtree sizes, O(h) each, h the height of the tree). Write ranks_list(values) with a sorted list: bisect_left finds the rank in O(log n), then insort inserts, shifting the tail in one C-level memmove: O(n) per insert, fast in practice. State each one's time.
  2. Check both against a brute-force count on 200 seeded sequences, including the empty one, a single value, and ascending and descending ones; count how many of each were hit and treat any exception as a failure.
  3. Measure 10,000 random arrivals. Then measure sorted arrivals of 1,000 and of 2,000, where an ordinary tree is a path. Print the times and ratios, and apply the 2x rule to the sorted rows; the random row moves with machine load (it dips under 2x when other programs run), so print its ratio only.
  4. Close with a sentence built from the verdicts: when does a hand-written tree pay here? Name what is beyond this topic: Fenwick trees and balanced trees.
Q58Near-Duplicates In A Sliding WindowHardMust Do

Given a list a of integers, an integer k >= 1 and an integer t >= 0, decide whether there is a pair of positions i < j with j - i <= k and abs(a[i] - a[j]) <= t. Return True or False; the empty list and a one-element list give False.

A binary search tree keeps every key of a node's left subtree below the node and every key of its right subtree above it. Its ceiling of x is the smallest key >= x, or None. A search tree answers "is any stored value within t of x?" with one ceiling: ask for the ceiling of x - t; a near value exists exactly when that ceiling is <= x + t.

  1. Write near_dup_tree(a, k, t): keep the last k values in a search tree. For each new value x, take the ceiling of x - t and return True if it is <= x + t; then insert x, and delete the value that has just left the window (a[j - k]). Write ceiling(root, x) with a loop. Argue why the window's keys are always distinct (a repeated value inside the window would already have answered True), so one delete removes exactly one key. State the time with h named.
  2. Write three competitors: the brute force over each window (near_dup_brute, O(n k)); a sorted list kept with insort and bisect (near_dup_list); and buckets of width t + 1 in a dict (near_dup_buckets): two values in the same bucket are within t, and only the two neighbouring buckets need checking, O(n).
  3. Check that all four agree on 300 seeded inputs with planted near pairs, including the empty list, a single value and sorted input, with both answers hit and any exception counted as a failure.
  4. On 10,000 seeded values in 0..10^9 with k = 1,000 and t = 10, time the tree, the list and the buckets; time the brute force on the first 2,000 values only, and compare all four on those 2,000 too. Apply the 2x rule to every verdict, and build the closing line from them. The tree against the list and the list against the buckets sit near the 2x bar and move with machine load, so print those two as ratios only.
Q59How Many Orders Build This TreeHard

Many insertion orders build the same search tree. The root must be inserted first; after that, the keys of the left subtree and the keys of the right subtree may interleave in any way, as long as each side's own keys go in an order that builds that side. So the number of orders that build a tree T with n keys is ways(T) = C(n - 1, size(left)) * ways(left) * ways(right), with ways(empty) = 1: choose which of the other n - 1 positions belong to the left side.

  1. Write count_orders(root) that computes it in one post-order pass, each node combining its two children's (size, ways) with math.comb. State its time and space.
  2. Check it against brute force: for every k up to 7, build the tree of every insertion order of 1..k (5,914 orders in all), count the orders per tree (identify a tree by its level-order list), and compare each tree's count with count_orders. At k = 7 all 429 trees must match; print the number of distinct trees per k, and the most orders any one tree has.
  3. Compute and print: a path-shaped tree (every node has at most one child) is built by exactly one order, and there are 2^(n - 1) path shapes, so 2^(n - 1) orders build some path (each key after the first must be the smallest or largest of those still to come; check a right path and a zig-zag path of 500 keys); the perfect 15-key tree has 21,964,800 of the 15! orders (about 1 in 60,000); and the count for the ten-key example tree T10. Python's int holds all of these exactly, where C's 64-bit integers would overflow past 20!.
  4. Cross-check with a second formula: the number of orders is n! divided by the product of every node's subtree size.
  5. Say in one line what DSA Topic 21 builds on this kind of pass.
Q60The Largest BST Inside A Binary TreeHard

In a binary tree whose values are arbitrary (nothing orders them), find the size of the largest subtree that is a search tree, where a subtree is a node and all its descendants. The whole tree may not be one, but a smaller piece inside it may be. DSA Topic 13 built random binary trees; its random_tree(n, rng, values) is pasted below (it builds len(values) nodes, so the values list must have exactly n entries).

  1. Brute force first: run is_bst on every node's subtree and keep the largest that passes (largest_naive). State its time, and why a path makes it O(n^2).
  2. One post-order pass instead (largest_bst): each subtree reports whether it is a search tree, its size, its smallest key and its largest key. A node roots a search tree when both children do and left max < key < right min; then its size is both children's sizes plus 1. Otherwise the answer so far is the larger of its children's. State time and space with h named.
  3. Check all three against the brute-force property check (every node's subtree walked for a violation) on every shape of up to seven nodes labelled by a seeded iterator (626 shapes, once in sorted order so the whole tree is a search tree and once in a seeded shuffled order), and on 300 seeded random_trees of 0 to 40 nodes. Some of the 300 must be search trees with two keys swapped. Count the empty tree, one node, sorted labels and swapped labels, and treat an exception as a failure.
  4. On a path of 800 nodes whose every subtree is a search tree, count the work in separate counted copies: nodes touched by the naive version against nodes visited by the one pass.
  5. Say in one line what DSA Topic 21 builds on this kind of pass.
Q61Recovering Two Swapped KeysHard

A binary search tree (BST) here holds distinct integer keys: every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. By mistake the keys of two nodes were swapped: each key now sits in the other's node, and no link changed. The tree is no longer a search tree, and the job is to put the two keys back.

The in-order list of a BST is increasing, so after a swap it has descents, places where a key is larger than the key that follows it. Two neighbours in order that were swapped make one descent; two keys that were not neighbours make two.

  1. Write find_swapped(root) with an explicit stack, in one in-order walk that remembers the previous node. It returns (first, second, descents): the first wrong node is the previous node at the first descent, the second wrong node is the current node at the last descent.
  2. Write recover(root): it swaps the two stored keys back in place and returns the root. A tree with no descent is left alone. State time and space (a Morris traversal, from DSA Topic 13, would make the space O(1); it is cited, not rewritten).
  3. Show the bug of repairing only the first descent's pair, on the path [3, None, 2, None, 1] (1 and 3 swapped), beside the true repair.
  4. Swap every pair of keys in every BST with 0 to 7 keys (fresh trees each time) and check recover restores the tree exactly (to_level equal). Count the pairs that make one descent and the pairs that make two, check the count of neighbour pairs independently, and count how many pairs the broken version gets wrong. Then check 300 seeded random trees (empty and single-node included), sorted-order paths in both directions, and one path of 100,000 nodes.
Q62Persistent Versions By Path CopyingHard

A persistent search tree keeps every version: an update returns a new root and leaves the old one exactly as it was. A binary search tree (BST) here holds distinct integer keys, smaller on the left and larger on the right. Path copying makes this cheap: an update copies only the nodes on the search path (a new root down to the changed spot) and shares every other subtree with the previous version (DSA Topic 13 did this on tuples; new here: the copies follow a search path).

  1. Write p_insert(root, x): it returns the root of a new version holding the keys of root and x, copying the path and nothing else. A key already present returns root itself. root is never changed.
  2. Write p_delete(root, x): it returns the root of a new version without x. It copies the path to x and, when x has two children, also the path down to its in-order successor (the smallest key above x). A missing key returns root itself.
  3. On a tree of 10,000 random keys, build 1,000 versions by 1,000 inserts of new keys. Print the height, the new nodes per insert, and the total number of new nodes against 1,000 full copies. Then insert 1,000 keys in increasing order into an empty tree and print the same counts.
  4. Check that every old version still has its keys, that unchanged subtrees really are shared objects, and that every version is a search tree: on every tree with 0 to 7 keys for every key from below the smallest to above the largest, and on samples of the large versions.
Q63Tree Sort And Its Worst CaseMedium

Tree sort inserts every item into a binary search tree (BST: distinct keys, smaller on the left, larger on the right) and reads the in-order list, which is increasing. This question shows that it is a hidden quicksort, and measures what that costs.

  1. Write tree_sort(items) with the kit's insert and in_list. It returns the distinct items in increasing order, since a key already present is left alone.
  2. Write tree_sort_counted(items), a separate copy that also counts key comparisons: one for each node an item is compared with on its way down. Check its output equals tree_sort.
  3. Write quicksort_comparisons(items): quicksort with the first item of each part as the pivot (parts are kept on an explicit stack), counting one comparison per other item in the part (distinct items). Claim: it makes exactly the comparisons the tree makes, because each node splits the items inserted after it the way that pivot splits its part (DSA Topic 9's quicksort). Check on 200 seeded inputs, empty, single and sorted ones included.
  4. Count comparisons for 2,000 random keys and for 2,000 sorted keys, and time tree_sort against sorted() for 10,000 random keys (min of 3, ratio, the 2x rule).
  5. Duplicates: the kit drops them. Write tree_sort_dups, whose node keeps a count of equal items, and check it against sorted() on 200 seeded inputs with many repeats.
Q64Ordering By Any KeyMedium

sorted(records, key=...) orders records by any key you compute. A binary search tree (BST: distinct keys, smaller on the left, larger on the right) can do the same: store each record under key(record) and compare keys only, never records.

  1. Write a KeyedBST class built with a key function. Its node holds (key, record). Methods: insert(record) (a key already present leaves the tree unchanged and returns False, otherwise True), records() (all records in key order), first(k) (the first k records in key order, fewer if the tree is smaller), and floor(key) (the record with the largest key at most key, or None).
  2. Keys must be distinct, so build them as tuples with a tie-breaker. Students are (name, score); the key (-score, name) puts the highest score first and breaks ties by name (DSA Topic 9's tuple keys). Show what happens with the key (-score,) alone: records with equal keys are lost.
  3. Check against sorted(records, key=...) on 300 seeded record sets, with bisect as the oracle for floor. Cover the empty set, a single record and records inserted in already sorted order. Do not use functools.

A record whose key changes after it was inserted sits in the wrong place and the tree silently breaks: shown later in this topic.

Q65Bulk Loading Versus One-By-OneMedium

All 100,000 keys are known at the start. A binary search tree (BST: distinct keys, smaller on the left, larger on the right) can be loaded three ways, and this question measures them:

  1. Bulk load: sorted() the keys once, then balanced_bst (the middle key is the root, recursively).
  2. One by one, random order: insert the keys in a shuffled order with from_keys.
  3. One by one, sorted order: insert them already sorted. This is a path, a linked list with extra steps. Never run it at 100,000. Time it at 1,000, 2,000 and 4,000 keys (one repeat at 4,000), print the ratio at each doubling, and project 100,000 from the 4,000 figure, labelled as a projection.

Time plain code with the min of 3 runs (inputs are built outside the timed function), print each height (in nodes), and check all loads give the same in-order. Decide whether the growth is quadratic from the counted comparisons (the sum of the node depths, which does not change from run to run), not from the times: a doubling ratio of 3 or more counts as quadratic (a linear cost doubles, a quadratic one quadruples; 3 is halfway). Print the time ratios too. The bulk against random-insert time ratio is printed with no verdict (it moves with machine load); build the closing line from the heights and from whether the sorted-insert growth is quadratic.

Q66Deleting A Range Of KeysHard

A binary search tree (BST) holds distinct integer keys, smaller on the left and larger on the right. To remove every key in [lo, hi] (both bounds inclusive) you could delete the k keys one at a time, at O(h) each, which is O(k h) for k keys. One recursive pass does better, because the search-tree rule says which side can hold keys in range.

  1. A node below lo can only have range keys in its right subtree: clean that, keep the node. A node above hi can only have them in its left subtree: clean that, keep the node.
  2. A node in range is removed: clean both subtrees, then join the two results into one tree. Every key on the left is below every key on the right, so the largest key of the left part (its rightmost node) becomes the root over both.
  3. Write delete_range(root, lo, hi): it removes the keys in place and returns the new root. A range holding no key, or lo > hi, changes nothing. Count visits (nodes stepped onto, including the join's walk down the right spine) in a copy with a counter.
  4. Check it against a filtered sorted list, with is_bst, for every lo <= hi from below the smallest key to above the largest on every BST with 0 to 7 keys, then on 300 seeded random trees with 30 ranges each, asserting visits < k + 2h + 1 (k keys removed, h the height in nodes before).
  5. Count visits against k one-at-a-time deletes for k = 10, 100 and 1,000 on a random tree of 10,000 keys. On a path of 2,000 nodes the recursion runs out; the one-at-a-time loop is the iterative partner.
Q67Keeping Sizes Right Through DeletesHard

A size tree is a binary search tree (BST: distinct integer keys, smaller on the left, larger on the right) whose nodes also store size, the number of nodes in the subtree rooted there, itself included. SizeNode, size_of, search, size_insert, select (k-th smallest, 1-based, IndexError out of range), rank (how many keys are below x) and sizes_ok (every size equals 1 plus its children's sizes) are given in the answer. Write size_delete(root, x), whose contract is:

  • It removes key x in place and returns the new root. A key that is missing changes nothing, not even a size: check first.
  • Every node whose subtree loses a node gets 1 taken off its size: each node on the path to x, and, when x has two children, also x's node itself and every node on the way down to its in-order successor (the smallest key above x). The successor's key moves into x's node and the successor's node is unlinked.
  1. Write the three cases in order: find x, take the sizes off on the way down, then unlink.
  2. Show the bug of forgetting the successor's path: on the tree built by inserting 2, 1, 4, 3, deleting 2 leaves a wrong size, which sizes_ok catches.
  3. Check 400 seeded scripts that mix size_insert, size_delete, select and rank against a sorted list, running sizes_ok and comparing the root's size after every operation. Count and assert that the scripts hit the empty tree, absent deletes, two-child deletes, root deletes and sorted insertion orders.
Q68Augmenting With Subtree SumsMedium

An augmented search tree stores one more number at each node. Here each node of a binary search tree (BST: distinct integer keys, smaller on the left, larger on the right) stores total, the sum of the keys in its subtree, itself included. The question is a range sum: the sum of the keys that lie in [lo, hi] (both bounds inclusive).

  1. Write SumNode and sum_insert(root, x): a key already present changes nothing; otherwise add x to the total of every node on the path down to the new leaf. It returns the root.
  2. Write sum_less(root, x), the sum of the keys below x, in one O(h) walk: whenever the walk goes right from a node, that node's key and all of its left subtree's total are below x, so add them. Then range_sum(root, lo, hi) is two walks, sum_less(root, hi + 1) - sum_less(root, lo) (integer keys).
  3. The alternative from DSA Topic 6, prefix sums on a sorted list, answers a range sum in O(1) after a lookup but needs an O(n) rebuild after every insert. Time both on n inserts, each followed by a range-sum query, for n = 1,000 and n = 2,000 (min of 3, built inputs outside the timing, same answers asserted). Print the time ratios with no verdict (they move with machine load), and decide whether the gap grew with n from counted work (prefix entries copied against tree nodes stepped onto), which is the same on every run.
  4. Check every total and every answer on every insertion order of 0 to 7 keys (all lo <= hi for up to 5 keys), and on 300 seeded random sets with negative keys.
Q69Deleting Lazily With TombstonesMedium

A binary search tree (BST: distinct keys, smaller on the left, larger on the right) can delete lazily: instead of unlinking a node, mark it dead (a tombstone). The shape never changes. DSA Topic 7's hash tables made the same trade, and tombstones that pile up cost there too.

  1. Write a node with a dead flag and a class TombBST with insert(x), delete(x), contains(x), keys() (the live keys in order) and purge(). contains treats a dead node as absent. Inserting a dead key revives its node (no new node). delete of a missing or already dead key returns False. purge() is an explicit call that rebuilds a balanced tree from the live keys and returns how many dead nodes it dropped; the tree never purges by itself.
  2. Build a tree of 10,000 keys in random order, delete 90% of them, and print live and dead nodes, the average number of nodes visited per search of a live key, and the memory a dead node holds. Compare with a tree that really unlinked the same keys (the kit's delete) and with the tree after purge().
  3. Check against a set on 300 seeded scripts of inserts, deletes, lookups and purges (keys from a small range so re-inserts and absent deletes happen). Cover the empty tree, a single key and sorted insertion orders, and count each.
Q70What Replaces A Hand-Written BSTMediumMust Do

Python has no search tree type, so what do programs use instead of the hand-written one? Measure, using 100,000 distinct integer keys held two ways, and decide from the printed ratios.

  • A size tree is a binary search tree (BST: distinct keys, smaller on the left, larger on the right) whose nodes store size, the number of nodes in their subtree. Built by inserting the keys in random order, its height is about 2.5 * log2(n). It promises O(h) for each of: rank(x) (how many keys are below x), select(k) (the k-th smallest key, 1-based), floor (the largest key at most x, or None), a range query (the keys in [lo, hi], both bounds inclusive; O(h + k) for k keys) and an insert.
  • A sorted list with bisect promises O(log n) for rank (bisect_left), floor (bisect_right) and the start of a range, O(1) for the k-th smallest (a[k - 1]) and O(k) to slice k keys out, but each insert (insort) shifts the tail of the list, which is O(n) (in CPython one fast C-level memory move).
  • A set (hash table) promises O(1) on average for exact lookups and nothing about order; a dict is the same hash table with values.

These helpers are written out in the answer: search, SizeNode, size_of, size_insert, select and rank. Write floor_key and range_keys for the tree. Then:

  1. Check both structures give identical answers on 300 seeded small sets (empty, single and sorted-order sets included).
  2. At 100,000 keys, time with the min of 3 runs, building every input outside the timing: 10,000 exact lookups (tree against a set), 1,000 range queries of about 100 keys, 1,000 k-th smallest queries (these three get a verdict), and 10,000 rank queries and 10,000 floor queries (tree against sorted list; these two print the ratio only, since it moves with machine load). Print each ratio as tree time / other time. A verdict needs a ratio of 2x or more in the same direction; anything less prints "no verdict". DSA Topic 13 already showed a sorted list beating a plain tree walk on a tree with no order; this is a search tree against its replacements.
  3. A changing set: 30,000 inserts of new keys into an initially empty structure, with a rank query after every 10 inserts, in the tree and in a sorted list with insort. Print the ratio only, no verdict for this row. DSA Topic 7 ended with the claim "a changing set of keys wants a tree": print "borne out" only if the tree is 2x or more faster, otherwise "not borne out at this size" with the ratio.
  4. Close with a decision built from the verdict variables, never typed: which structure won each row that has a verdict, and when you would still write your own tree. sortedcontainers is a third-party library that makes a sorted list scale; it is named, never imported.
Q71The Validator That Trusts ZeroEasy

A student's bounds validator for a binary search tree passes each node a lower and an upper bound (None for no bound) and tests if (lo and node.val <= lo) or (hi and node.val >= hi): return False. It passes every example on positive keys.

  1. Find the smallest tree it wrongly accepts by scanning every labelling of every shape with 0, 1, 2, 3 nodes using distinct keys from -2..2 (a labelling places keys on the nodes in in-order position, in any arrangement), comparing with the brute-force search-tree property check. Print the tree beside the truth and explain the bug.
  2. Fix it with is not None and show the fix rejects that tree.
  3. A second fix starts the bounds at float('-inf') and float('inf'), so no test is ever skipped. Show it is right on the numeric tree, then run it on a three-word tree and print the type of the error it raises. Which fix is the general one? Show the broken check failing on string keys too (the empty string is falsy).
  4. Check the broken, the is not None and the infinite-bound validators against the brute-force property on every labelling of every shape up to 4 nodes with keys from -2..2. Print how many trees were checked and how many each gets wrong.
  5. Fuzz the fixed validator on 300 seeded trees (empty, single node and sorted insertion orders counted), half of them with one key overwritten so the order breaks. The oracle is "the in-order list is strictly increasing". Count any exception as a failure.
Q72The Recursion That Runs Out On Sorted DataHardMust Do

A binary search tree (BST) is a binary tree of distinct keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. Height counts nodes on the longest path from the root down (empty tree 0, one node 1). Python keeps one stack frame for each call that has not yet returned, and refuses to go deeper than sys.getrecursionlimit() frames (1,000 by default in CPython), raising RecursionError.

DSA Topic 13 showed recursion running out on a tree shaped like a path. What a search tree adds is that nobody has to build that path on purpose: inserting keys in sorted order makes each key the right child of the one before, so the height is n.

Write three recursive functions, each with one call per level of the tree:

  • insert_rec(node, x) puts x into the subtree rooted at node in place and returns that subtree's root (a new node when node is None); a key already present changes nothing.
  • is_bst_rec(node, lo=None, hi=None) returns True when every key lies strictly between the bounds its ancestors set (None means no bound).
  • search_rec(node, x) returns the node holding x, or None when x is missing.

Their iterative partners are a loop for search and insert (O(1) extra space) and an explicit stack for validation. Then:

  1. Insert 1, 2, ..., 2,000 in that order with insert_rec, stopping at the first error. Print the error's type, and show (as booleans, never as a count) that the tree kept so far is a valid BST holding fewer than 2,000 keys, and that its height is below the limit.
  2. Build the same 2,000-key path directly, print its height against the limit, and run the recursive validator on it: print the outcome's type.
  3. Run the iterative versions on a path of 100,001 keys: validate it, search for the largest key, and build 2,000 sorted keys by iterative inserts.
  4. Build a BST from 10^5 keys inserted in a seeded random order. Print its height against the limit, and show the recursive validator and search succeed on it.
  5. On 200 seeded shallow builds (empty, single node and sorted orders counted), check that the recursive and iterative versions agree with each other and with a sorted list. Count any exception as a failure.

Raising the recursion limit only moves the cliff (DSA Topic 13 showed this): each frame costs memory, and a longer path fails again at the new limit. The fix is the loop or the explicit stack.

State the time and space of each version, with h named: about log2(n) when balanced, about 2.5 * log2(n) for a random insertion order, n for a sorted one. Never print the depth or key count at which something failed: it depends on the interpreter, not on the tree.

Q73The O(log n) That Is O(n)Hard

Three claims you will hear about BSTs. Test each one with counts, not with a clock, and print the claim, the count and the corrected statement, the last built from the counted numbers.

  1. "Insert is O(log n)." Write a counted copy of insert that returns the nodes visited, and check it builds the same tree as the plain insert. In a sorted build of 2,000 keys, assert that the i-th insert visits exactly i - 1 nodes for every i, and print the total beside n(n - 1)/2 and beside a random-order build of the same keys.
  2. "The k-th smallest is O(log n)." Find the median of 10^4 random keys by an in-order walk that stops at k (1-based), counting pops and pushes, and assert pushes <= k + h. Then build the same keys as a size tree (each node storing its subtree size) and count the nodes select visits.
  3. "The successor is O(1)." On a 1,000-node right path built with parent references (the PNode tree written earlier in this topic), walk every successor from the minimum. Print the worst single call and the total, and assert the total is at most 2n - 1.
  4. Fuzz the counted copies against the plain functions and a sorted list on 200 seeded builds (empty, single node and sorted orders counted), counting any exception as a failure.
Q74Deletes That Lose NodesHardMust Do

A binary search tree (BST) is a binary tree of distinct integer keys in which, at every node, every key in the left subtree is smaller than the node's key and every key in the right subtree is larger. The in-order successor of a node with two children is the leftmost node of its right subtree: it holds the smallest key larger than the node's, and it has no left child.

The contract of delete(root, x): it removes key x in place (nodes are re-linked, no new tree is built) and returns the root, which is new when the root itself was removed (its only child, or None when the tree became empty). A missing key changes nothing: the same root comes back and no error is raised. The node holding x falls into one of three cases:

  • no child: its parent's reference becomes None;
  • one child: its parent's reference skips to that child, whichever side it is on;
  • two children: copy the successor's key into the node, then unlink the successor node, which has at most a right child, by the first two cases.

Here are four believable deletes, each with one bug:

  • B9 copies the successor's key, then removes that key by calling delete again from the root.
  • B10 splices a one-child node out by always taking its left child.
  • B11 only ever changes a parent's reference, so it has no branch for the root.
  • B50 unlinks the successor by setting its parent's reference to None.
  1. Write the four, sharing one find(root, x) that returns the parent and the node. Predict from the code what each does wrong, and its smallest failing tree, before running it, and record each prediction as a comment.
  2. Find each bug's smallest failing tree. Scan every BST on keys 1..k for k = 0..7 (626 trees, a fresh copy each time) in increasing size, deleting every key and two absent ones. Print the result beside the right one, and print the error's type when it raises.
  3. Write one fuzz harness: 300 seeded scripts of mixed inserts and deletes on keys 0..2n, compared with a sorted list after every step. The check fails a script on any exception. Count the failed scripts for each variant and for the correct delete. For the correct delete, also count the empty-tree, single-node, sorted-start, leaf, one-child, two-children, root and absent cases, and assert each was met.
  4. Say in one line each what fixes the four bugs.
Q75Successors That SkipMedium

The contract: successor(root, x) returns the smallest key greater than x, whether x is in the tree or not, and None when no key is greater. Three versions break it:

  • B15 records the candidate on the wrong turn (when it goes right past a key that is not above x, instead of when it goes left past one that is).
  • B55 first searches for x, the way a node's successor is found, and returns None when x is absent.
  • B58 compares with >=, so a key equal to x counts as greater.
  1. From the code alone, predict each one's smallest failing case (tree and x), and write the predictions down in the answer.
  2. Confirm them by scanning every BST on keys 1..k for k = 0..7 with every x in 0..k + 1, comparing with bisect_right on the sorted keys. Print each smallest failure, whether it matches the prediction, and how many present and absent x each version gets wrong.
  3. Two of the bugs share a smallest case. Find an input that tells them apart.
  4. Fuzz the correct version on 300 seeded trees, sorted insertion orders included, against bisect_right, asking for every x in range. Count the empty-tree, single-node and sorted cases, and count any exception as a failure.
Q76Keys That Break The OrderEasy

A search tree assumes two things about its keys: any two compare consistently (exactly one of <, ==, > holds), and a key never changes while it is in the tree. Break each assumption and watch what the kit's insert, search and is_bst do.

  1. float('nan') compares False with everything. Find the smallest insertion order of keys drawn from 1.0, 2.0 and nan that loses a key. Then insert 2.0, 1.0, nan, 3.0 and show nan is dropped without an error. Insert nan first, then 1.0, 2.0, 3.0, and show the tree holds only nan while is_bst still says True.
  2. Insert an int and then a str, and print the type of the error.
  3. Change a stored key in place. Find the smallest case by scanning every BST on keys 1..k (each key changed to each absent value in 0..k + 1) for a key that search can no longer find. Then change 40 to 65 in the tree built from 50, 30, 70, 20, 40, 60, 80, and print the in-order, is_bst and search(65). (DSA Topic 7 showed the same trap for a dict key.)
  4. Fix both problems. Reject nan at insert with ValueError, keep keys immutable, and re-key by delete then insert. Show both fixes working.
  5. Fuzz the fixes on 300 seeded scripts against a sorted list: float keys with nan offered, then re-keys. Count the empty, single-node, sorted, nan-refused and re-key cases, and count any exception as a failure.
Q77Duplicates That HideHard

When a tree stores repeated keys, every function must agree on where the copies go. Three bugs break that agreement. Show each one on its smallest case, found by scanning every sequence of the keys 1 and 2 of length 1 to 4, beside the truth from a Counter or a sorted list.

  1. B8: insert sends an equal key right, but count(x) walks left after the first match, as if the copies had gone left. Show the smallest case, then insert 5, 5, 5 and count.
  2. B37: equal keys go left, and the left-walking count is right for that tree, until rotate_right at the root carries a copy to the right side. Print the tree and the count before and after the rotation.
  3. B77: in an equal-left tree, a range walk goes left only when key > lo, so a copy of lo in the left subtree is skipped. Show [2, 2] on a tree holding 2 twice, beside the fixed walk.
  4. The robust fix is the (key, seq) tuple policy from earlier in this topic, where seq is an insert counter: every stored key is distinct, and copies are counted and removed (oldest first) by bounded walks over the tuples. Show what it adds here: a rotation at the root no longer changes a count.
  5. Fuzz the tuple tree on 300 seeded scripts of inserts, single removals (a missing key changes nothing) and root rotations. After every step, check the in-order keys against the Counter's sorted elements, and check a count against the Counter. Count the empty, single-node, sorted-start, repeat, rotation and absent-removal cases, and count any exception as a failure.
Q78Rotations That Break ThingsMedium

A rotation must keep the in-order unchanged, and in a size tree (each node storing its subtree size) every stored size must stay right. Two bugs break this:

  • B21: a left rotation drops the middle subtree (the new top's old left child) instead of moving it under the old top.
  • B45: a size tree's left rotation recomputes the new top's size first and the old top's second, so the new top reads a stale child size.
  1. Rotate left at every node that has a right child, in every BST on keys 1..k for k = 0..7 (fresh copies, each re-linked into its parent). Check with the in-order list and the brute-force property. Print how many rotations B21 gets wrong, its smallest failing case beside the right result, and the kit's rotations on the same bed.
  2. Do the same for B45 on the same trees as size trees, checked with sizes_ok. Print the smallest case's root size beside the true size, then write correct size rotations both ways and check them.
  3. Fuzz the fixed size rotations: 300 seeded trees (empty, single node and sorted orders counted), 20 rotations each at random nodes, checked against a sorted list and sizes_ok. Count any exception as a failure.
  4. State the rule for the order in which sizes are recomputed.
Q79Deleting While You WalkMedium

A student deletes keys during a lazy in-order walk: for each key the walk yields, if it should go, call the kit's delete. (DSA Topic 13 changed a tree while walking it. Here the cause is specific to search trees: deleting a node with two children copies its successor's key into it.)

  1. Delete the even keys during a walk of [4, 2, 6, 1, 3, 5, 7] (level order). Print the keys the walk saw and the tree afterwards, and explain why 3 and 5 are never seen.
  2. That example comes out right by luck. Find the smallest case that comes out wrong by scanning every BST of ALL_BST with up to 5 keys and every subset of its keys, compared with a set difference. Print the keys seen, the tree left and the tree wanted.
  3. Fix it: collect the keys to delete first, then delete them. Check the fix on the same bed.
  4. Fuzz the fix on 300 seeded random trees and paths against a sorted list, with a random 40% of the keys deleted. Count the empty-tree, single-node and sorted cases, and count any exception as a failure.
  5. Show what Python's own set does when changed during iteration.
Q80Range Queries That MissEasy

The contract: range_keys(root, lo, hi) returns every key with lo <= key <= hi, in increasing order. A range count returns how many there are. Three versions break it:

  • B18 returns as soon as it meets a key above hi, before looking at that node's left subtree.
  • C80 tests the lower bound strictly (lo < key).
  • B80 is a range count that adds 1 for every node it visits, in range or not.
  1. Write the correct version as an explicit-stack in-order walk pruned by both bounds, then write the three broken versions.
  2. Scan every BST on keys 1..k for k = 0..7 with every lo <= hi in 0..k + 1, comparing with a sorted-list filter. Print how many (tree, range) pairs each version gets wrong, and its smallest failing case beside the truth.
  3. Show C80 on keys 1..3 with the range [1, 3].
  4. Fuzz the correct version on 300 seeded trees, including a sorted-order path of up to 300 keys, with 20 ranges each, against bisect_left/bisect_right slices of a sorted list. Count the empty-tree, single-node, sorted and empty-range cases, and count any exception as a failure.
Q81The Balance Check That Trusts Stored HeightsMedium

An AVL tree is a binary search tree in which, at every node, the heights of the left and right subtrees differ by at most 1 (heights count nodes: the empty tree is 0, one node is 1). check_avl(root) is the reference checker: it recomputes every height from the children, returns the height of an AVL tree, and raises ValueError naming the node if the search order breaks or a balance factor (left height minus right height) is beyond 1. Two checkers that a student might write both say "balanced" when they should not. This question catches each of them.

  1. Give each node a height field, set to 1 when the node is made. Write a plain insert for these nodes (it links the new leaf and never touches any height field), and a checker check_avl_stored that trusts the stored heights of the two children. Scan every insertion order of up to 7 keys, smallest first, and print the first one where the stored checker says balanced and check_avl raises, beside the truth.
  2. Write check_avl_one_sided, which recomputes heights correctly but raises only when the left side is more than 1 taller. Show [1, None, 2, None, 3] (a right path of three) passing it.
  3. Compare each checker with check_avl on every binary search tree of up to 7 keys (626 trees), and print how many trees each wrongly accepts. A tree-by-tree oracle that uses the plain height of a tree (in nodes) at every node must agree with check_avl on all of them.
  4. Fuzz the fixed checker, check_avl, on 300 seeded scripts of plain inserts and deletes (some scripts insert in sorted order, some do nothing at all) against a sorted list: the tree's in-order list must equal the sorted list, and the verdict must equal the oracle's. Count the empty trees, single nodes and sorted scripts hit, count any Exception as a failure, and print the failures (0).
  5. State the fixes: recompute the heights while checking, or update the field of every ancestor after every change (what a real AVL insert does; named here, never built).
Q82The Red-Black Checker That Looks Down One SideMedium

A red-black tree is a binary search tree whose nodes are coloured red or black so that four rules hold: the order is a search tree, the root is black, no red node has a red child, and every path from the root down to a missing child passes the same number of black nodes (the black height; a missing child counts as black and is not counted). check_rb(root) is the reference checker: it returns the black height of a valid tree and raises ValueError naming the first rule broken. RBNode(val, red) holds the colour as a boolean, and rb_from_level(values, reds) builds a tree from a level-order list with None gaps and paints the keys in the set reds red. Two checkers a student might write each skip half of a rule. This question catches them.

  1. Write check_rb_leftmost: it checks the order, the root and every red-red pair, but takes the black height from the leftmost path only and never compares another path. Show the all-black [1, None, 2] passing it.
  2. Write check_rb_left_red: it checks everything except that it looks for a red child on the left only. Show [1, None, 2, None, 3] with 2 and 3 red passing it.
  3. Build every colouring of every tree shape of up to 5 nodes (the keys 1..k in order, each node red or black: 1,619 coloured trees, counting the empty tree once). For each liar print the smallest coloured tree it wrongly accepts, found by scanning in increasing size, beside the message check_rb gives, and print how many of the coloured trees each wrongly accepts. A path-enumerating oracle (list the colours along every root-to-gap path) must agree with check_rb on every one.
  4. Fuzz the fixed checker, check_rb, on 300 seeded coloured trees: valid trees with 0 to 2 colours flipped, random search trees with random colours, and sorted-order paths. Compare each verdict (and the black height when accepted) with the oracle, check the tree's in-order list against a sorted list of its keys, count the empty trees, single nodes and sorted paths hit, count any Exception as a failure, and print the failures (0).
  5. Say which rule each liar skips, and what a real red-black insert adds: it repairs these rules with recolourings and rotations after every change (named here, never built).
Q83Persistent Versions That LeakHard

A persistent search tree keeps every old version intact: an insert returns the root of a new version and leaves the old root and everything under it unchanged. It does this by path copying: it makes a fresh copy of each node on the path from the root down to the new key's place, and the new nodes point at the old, untouched subtrees for everything off that path (DSA Topic 13 did the same on tuples). p_insert(root, x) takes the root of a version (or None) and returns the root of the new one; a key already present returns the old root. The bug here is a student's: the insert copies a node when it goes left, but when it goes right it writes into the old node.

  1. Write the correct p_insert (recursive; the trees are shallow) and the leaky p_insert_leaky that does node.right = ... on the old node when x is larger and returns that same node.
  2. Find the smallest failing input: scan every insertion order of up to 6 keys, smallest first, keeping the list of versions and a to_level() snapshot of each one (the level-order list with None for a missing child) taken before the next insert; after each insert compare every old version with its snapshot. Print the first leak found, with the old version's snapshot beside what it shows now.
  3. A second, independent check: the new version must hold new objects on the whole search path of the old version. Collect the id of each node on the old path and of each node in the new version, and test that the two sets share nothing (the ids are compared, never printed). Also check that every node off the path is shared, so a correct insert makes exactly path length + 1 new nodes.
  4. Run both inserts through 300 seeded scripts (0 to 30 inserts, keys in 0..2n so keys repeat, every fifth script in sorted order, every one starting from the empty tree) against a sorted list. Count the scripts that start empty, have a single-node version, are sorted, or re-insert a present key. Catch any Exception as a failure. The correct insert must have 0 failures; the leaky one must be caught, and its first leak is printed.
Q84Merges And Serialisations That Make PathsMedium

Two ways of combining or saving a search tree look harmless and quietly turn it into a path. The tree's shape is decided by the order the keys are inserted in, so any code that feeds keys to insert in sorted order builds a path of height n and makes every later operation O(n). (Heights count nodes: one node is 1. from_keys(keys) inserts keys in the order given and ignores a repeat; balanced_bst(sorted_keys) builds the shortest tree of sorted keys.)

  1. Merging. merge_by_insert(a, b) inserts the keys of tree b, read in b's in-order, into tree a. Build a from 1,000 shuffled keys 0..999 and b from 1,000 shuffled keys 1000..1999 (seeded random_bst), and print the heights of a, b and the merge. Assert the merge is taller than 1,000.
  2. Saving. save_inorder(root) writes the in-order list and load_by_insert(keys) rebuilds by inserting them in that order. Print the height before and after for a balanced tree of 7 keys, one of 15 keys and a shuffled tree of 1,000 keys, and assert the reload of the 1,000-key tree is a path.
  3. A dict in key order. A dict iterates in insertion order. Fill one with the keys 0..1999 in order and call from_keys on it; print the height (2,000).
  4. The fixes (both were built earlier in this topic: merging two search trees through their in-order lists, and saving the pre-order and rebuilding). Merge the two in-order lists with a two-pointer merge and build with balanced_bst; or save the pre-order (each node before its children), whose reload through from_keys rebuilds the very same tree. Show the merged height and that the pre-order reload has the same to_level() list as the original.
  5. Fuzz both fixes against a sorted-list oracle on 300 seeded pairs of trees with 0 to 40 keys each (the keys of the two overlap on purpose; some pairs are empty, single-node, inserted in sorted order, or have b entirely above a): the merge's in-order must equal the sorted union, its height must be the minimum, and the pre-order reload must equal the original tree. Count each case hit, count any Exception as a failure, and print the failures (0).
Q85The Suite For Any BSTHardMust Do

Write a test suite that can be run against any implementation of an ordered set of distinct integer keys, and use it to tell a correct binary search tree from six broken ones. The contract an implementation must meet is a class Impl whose instances start empty (Impl()) and have these methods:

  • insert(x): add key x; if x is already present nothing changes. Inserting into an empty set must work.
  • delete(x): remove key x; if x is not present nothing changes and no exception is raised.
  • contains(x): True or False.
  • minimum(): the smallest key, or None when the set is empty.
  • between(lo, hi): the sorted list of keys with lo <= key <= hi (both ends inclusive), [] when none qualify or lo > hi.
  • kth(k): the k-th smallest key, 1-based (kth(1) is the minimum); IndexError when k < 1 or k is more than the number of keys.
  • successor(x): the smallest key strictly greater than x, or None; x need not be present.
  • keys(): every key in ascending order.
  1. Build the reference implementation TreeSet on a plain binary search tree (the ordinary insert, delete and search of a binary search tree, with an iterative minimum, between, kth, successor, and the in-order list).
  2. Write one test per operation, plus a test of deleting absent keys, a test of deleting present keys, and a randomised script test. Each test generates its cases smallest first and returns the first case where the implementation differs from a sorted-list oracle. The cases come from every binary search tree of up to 6 keys (built through the public insert, in the tree's pre-order, so the shape is reproduced), every insertion order of up to 6 keys, and 300 seeded scripts of 40 mixed operations on keys 0..24.
  3. A case counts as failed if the answer is wrong or any Exception is raised, naming its type. Count how often the suite reached an empty set, a single key, a sorted insertion order and an absent key, and assert each count is above 0.
  4. Run the suite on TreeSet (every test passes) and on six planted bugs, each in a subclass: S1 insert into an empty tree raises AttributeError; S2 deleting a missing key raises KeyError; S3 minimum steps left only once; S4 between treats hi as exclusive; S5 kth is 0-based; S6 a node with two children takes the predecessor's key but the successor's node is unlinked. Print, for each bug, the first test that failed with its smallest input, and assert it is the test aimed at that bug.
Q86The Ordered MapMini-ProjectMust Do

Python has a dict for lookup and a sorted list with bisect for order, but no container that does both while changing. Build one: an OrderedMap class on a binary search tree of (key, value) nodes, where a binary search tree keeps every key in a node's left subtree smaller than the node's key and every key in its right subtree larger, and where each node also stores the size of its subtree (itself included), so ranks come from one walk down. Keys are distinct integers; the empty map is a tree that is None. Heights count nodes (one node is 1). The map never rebalances by itself: only rebalance() does.

Every method's contract:

  • m[key] = value: add the pair, or replace the value if the key is present (the length does not change).
  • m[key]: the value; KeyError if the key is missing. del m[key]: remove the pair; KeyError if missing, and nothing changes.
  • key in m: True or False. len(m): the number of keys, read from the root's stored size (0 when empty).
  • for key in m: the keys in ascending order, produced lazily by a generator with an explicit stack (any depth).
  • min_key() and max_key(): the smallest and the largest key, None when the map is empty.
  • floor_key(x): the largest key <= x, or None; ceiling_key(x): the smallest key >= x, or None. x need not be present.
  • items_between(lo, hi): the list of (key, value) pairs with lo <= key <= hi (both inclusive) in key order; [] when none qualify or lo > hi.
  • select(k): the k-th smallest key, 1-based (select(1) is the minimum); IndexError if k is below 1 or above len(m). rank(key): how many keys are strictly smaller than key; key need not be present.
  • rebalance(): rebuild the tree in place as a balanced one (height ceil(log2(n + 1))) with the same pairs, and correct sizes.
  1. Build the class, with the pointer comment where a node is linked and a one-line note on what Python code would use instead.
  2. Trace a small session on ten keys.
  3. Fuzz it against a dict plus a sorted key list on 500 seeded scripts of 30 operations on keys 0..29, comparing every result (an exception type counts as a result, any other Exception is a failure) and calling is_bst(root) (true when every key lies strictly between the bounds its ancestors set) and sizes_ok(root) (true when every stored size is 1 plus its children's stored sizes) after every operation. Some scripts start with sorted inserts, some begin on an empty map. Assert that the empty map, a single key, a sorted load, a replaced key, a missing key and a rebalance() were all hit, and print the counts.
  4. Load 2,000 sorted keys, print the height before and after rebalance(), and assert it falls to ceil(log2(n + 1)).

State time and space per method, with h named (about log2(n) balanced, about 2.5 * log2(n) for a random order, n for a path).

Q87The Calendar BookerMini-Project

Build a room calendar. A booking is a half-open interval [start, end) of whole minutes, start < end: it holds the minutes start, start + 1, ..., end - 1, so a booking that ends at 90 and one that starts at 90 do not clash (unlike the inclusive ranges used for key queries elsewhere in this topic; DSA Topic 6 compared inclusive and half-open ranges). Two bookings clash when they share a minute. Bookings are stored in a binary search tree keyed by the tuple (start, end); because no two stored bookings overlap, ordering by that tuple is ordering by start. The empty calendar is a tree that is None.

The key idea: when a new booking [s, e) comes, only two stored bookings can clash with it. The one with the largest start <= s (the floor) clashes if it ends after s; the one with the smallest start >= s (the ceiling) clashes if it starts before e. Everything else is further away, so a booking costs O(h) instead of a scan of all n.

Every method's contract:

  • book(start, end): ValueError unless start < end; return True and store the booking if it clashes with nothing, otherwise return False and change nothing (including a second booking with the same start). On an empty calendar any valid booking succeeds.
  • cancel(start): remove the booking that starts at start and return True; False (nothing changes) if no booking starts there.
  • gaps(lo, hi, length): the list of free stretches (a, b) inside [lo, hi), in order, each at least length minutes long and as long as possible (a free stretch is never split); ValueError if length < 1; [] if lo >= hi.
  • first_free(after, length): the smallest t >= after such that [t, t + length) clashes with nothing; ValueError if length < 1. The calendar has no end, so an answer always exists.
  1. Write the floor and ceiling searches on tuple keys, a lazy in-order walk that starts at a given key, and the calendar on an ordinary binary search tree insert and delete (keys are the (start, end) tuples).
  2. Trace a small session: a booking, a touching booking, a clash from each side, gaps, first_free and a cancel.
  3. Check every method against a brute force, a plain list of bookings tested pair by pair plus a set of busy minutes scanned minute by minute, on 300 seeded scripts of 30 requests with times in 0..79. Count the empty calendars, single bookings, sorted placements, clashes, touching bookings accepted and missing cancels reached, and count any Exception as a failure.

State time and space per method, with h named (about log2(n) balanced, n for a path) and k the bookings a range walk visits.

Q88The BST DoctorMini-ProjectMust Do

Someone hands you a binary tree and says "it is a search tree". Write diagnose(root), which examines the tree and reports on it, and repair(root), which fixes what can be fixed. Definitions you need: a binary search tree has every key in a node's left subtree smaller than the node's key and every key in its right subtree larger (all keys strictly different); the bounds of a node are the keys of its ancestors that squeeze it, lo the nearest ancestor it lies to the right of and hi the nearest ancestor it lies to the left of (None for no bound), and a key is valid when lo < key < hi; a tree is balanced (AVL) when at every node the heights of the two subtrees differ by at most 1; heights count nodes (the empty tree is 0, one node 1), and the ideal height of n nodes is ceil(log2(n + 1)). The empty tree is None. A node has val, left and right, and a "size tree" also has a stored size (the number of nodes in its subtree, itself included); a node class without a size field is a plain tree. Every walk must be iterative, so a path of 10^5 nodes is diagnosed without recursion.

diagnose(root) returns a dict with these fields. "Pre-order" means the node, then its left subtree, then its right subtree.

  • count, height, ideal.
  • bst: True when no key breaks its bounds; violation: the first node in pre-order whose key breaks its bounds, as (key, lo, hi), or None.
  • duplicates: the sorted list of keys that occur more than once.
  • balanced: True or False; unbalanced: the last node in pre-order whose subtree heights differ by more than 1 (so everything below it is balanced), as (key, left height minus right height), or None. Heights are recomputed, never trusted.
  • sizes: None for a plain tree; for a size tree True when every stored size is right, otherwise the last node in pre-order with a wrong stored size, as (key, stored, true).

repair(root) returns (root, actions), a list of text actions applied in this order. (1) If the tree is not a search tree and swapping the keys of exactly two nodes makes it one, swap them in place ("swapped a and b"); if no such swap works, change nothing and report "cannot repair the order". (2) If a size tree has a wrong size and its order is now right, recompute every stored size in place ("sizes recomputed"). (3) If the order is right and the height is more than 3 times the ideal height, rebuild balanced from the in-order keys, with the same node class ("rebuilt balanced"). A healthy tree gets ["nothing to do"].

  1. Write both, with a helper that lists the nodes in pre-order with each node's parent index and bounds, and finds heights and true sizes in one backwards pass (a node comes after its parent in pre-order, so reading the list backwards sees children first).
  2. Run them on ten patients: a healthy tree, the trap [10, 5, 15, None, None, 6, 20] (level order, None for a missing child; every parent-to-child comparison is fine, yet 6 is in 10's right subtree, as the left child of 15, so it must be above 10), two swapped keys, a path built from sorted inserts, stale sizes, a duplicate key, the empty tree, a single node, a search tree that is not balanced, and a path of 10^5 nodes.
  3. Check 300 seeded damaged trees (healthy, two swapped keys, a stale size, a duplicate, a sorted-insert path, random keys) against a brute force that recurses with full ancestor lists, a plain height function, and a brute-force search-tree check (for every node, everything in its left subtree is smaller and everything in its right subtree larger). Count the empty trees, single nodes and sorted paths hit, count any Exception as a failure, and check each repair against a sorted list of the original keys.

State time and space of each function, with h named where it matters.

Q89The Snapshot StoreMini-Project

Build a key-value store that remembers every version of itself. An update never changes a tree that already exists: it copies the path from the root down to the changed key (about h new nodes, h the height) and points the copies at the old subtrees for everything else, so two versions share almost all their nodes. This is the persistent search tree from earlier in this topic with values, and the same sharing idea as the undo tree of DSA Topic 13, which kept every branch of an edit history. The empty tree is None; a version is the root of one tree.

Every method's contract:

  • Store(items=()): version 0 holds the (key, value) pairs given, built as a balanced tree; ValueError if a key repeats.
  • put(key, value, base=None): a new version made from version base (the newest version if base is None) with key set to value (added, or replaced if present). Returns the new version number (the next integer). IndexError if base does not exist.
  • delete(key, base=None): a new version without key; returns its number. KeyError if the key is missing, and no version is created.
  • get(key, version): the value; KeyError if missing; IndexError if the version does not exist.
  • items(version): the sorted list of (key, value) pairs.
  • diff(v1, v2): (added, removed, changed), three sorted lists of keys: in v2 but not v1, in v1 but not v2, and in both with different values. It skips any subtree that the two versions share (the very same object, tested with is), so after puts its cost follows the changed paths and not the size of the store; a delete that moves a successor up into a node's place can cost a full walk of the subtrees below that spot, and one such diff is measured. It counts its node visits in visits.
  1. Write the store (recursive put and delete are fine: the trees are shallow) with a counter of the nodes ever created.
  2. Trace a small store with a branch, and print diff for two versions.
  3. On a store of 10,000 keys take 1,000 updates (a mix of new keys and replaced ones). Print the nodes created per update against the bound h + 1, the visits of diff for neighbouring versions and for versions 0 and 1,000 against the 2n visits of a full walk, and the nodes held by all 1,001 versions against 1,001 full copies (the count, and the bytes at sys.getsizeof of one node).
  4. Check the store against dict snapshots on 200 seeded scripts (some branching from older versions, some sorted, some starting empty): after every step, every version still reads exactly its snapshot, and diff equals the dict comparison on random pairs. Assert that updating never changed an older version, count any Exception as a failure, and print the coverage.

State time and space per method, h being the height and k the nodes diff visits.

Q90The Best-Fit Allocator, IndexedMini-Project

DSA Topic 12's free-space manager kept the free blocks in an address-ordered linked list and found the best fit (the smallest free block that is big enough, the lowest address on a tie) by walking all F blocks, O(F) per request. Index the same free blocks with two search trees so no walk is needed. Memory is capacity units numbered from 0; a free block is a pair (start, size); the empty tree is None.

  • Tree by size: keys (size, start). The best fit for a request of n units is the ceiling (the smallest key >=) of the probe (n, -1): the smallest size that fits, and among equals the lowest start. One O(h) search, h the tree's height.
  • Tree by start: keys (start, size). When a block is freed, its two possible neighbours are the floor (the largest start <= the freed start) and the ceiling (the smallest start >=) in this tree. A neighbour that touches the freed block (start + size equals the next start) is merged into one bigger block. No union-find (DSA Topic 18) is needed: two floor/ceiling searches find the only blocks that can touch.

Contracts:

  • allocate(n): ValueError if n <= 0. Takes the best-fitting free block, hands out its first n units, puts any remainder back as a free block, and returns the start; returns None (and changes nothing) when no block is big enough.
  • free(start): start must be the start of a block handed out by allocate and not yet freed, else ValueError. The block returns to the free blocks and merges with a touching free neighbour on either side (both sides possible).
  • Every free block is in both trees, no two free blocks touch, and free units + allocated units == capacity always.
  1. Write the allocator on the plain insert and delete, with floor and ceiling searches that count the nodes they visit, and a work counter for every tree operation (the search of a delete counts, and so does the walk down to a two-child delete's successor).
  2. Write a brute-force allocator: a sorted list of free blocks, best fit by scanning the blocks (all of them, except that it stops at an exact fit, as the linked-list manager did), and a free that finds its place by bisect and merges list neighbours; plus a bitmap of units that must never be marked twice.
  3. Drive both with seeded request streams and compare every result (and every exception type, with some bad requests mixed in). After every call assert that the free and allocated units add up to the capacity; every 100 calls recount both trees against the brute list and against the maximal free runs of the bitmap.
  4. Cover small capacities (0 to 40 units, 300 streams: empty free space, a single free block, ascending allocation and freeing, no-fit requests, exact fits, two-sided merges, bad frees), then run the real workload: 10,000 requests on 20,000 units. Report the work per call against the O(F) walk, and name a winner only if the ratio is at least 2x. Then repeat the count on a fragmented memory (60,000 units, 2,400 small blocks, every other one freed in random order, then 4,000 requests, F about 500) and say whether the ratio grows with F.

State time and space per method, with F the number of free blocks and h the tree height (about log2(F) balanced, F on a path).

Q91The Running LedgerMini-Project

Build a running ledger. Transactions (timestamp, id, amount) arrive mostly in time order, but some arrive late. Timestamps, ids and amounts are ints, and ids are distinct. Store them in a binary search tree keyed by the tuple (timestamp, id), so two transactions at the same time are still distinct keys and sort by id. Each node also stores two augmented fields: size, the number of nodes in its subtree, and total, the sum of the amounts in its subtree, both counting the node itself. The subtree sums from earlier in this topic summed keys. Here they sum a separate amount, so a balance at time t becomes a prefix sum over the time order.

The empty ledger is the tree None. The class must keep these contracts:

  • add(t, id, amount) returns True. If (t, id) is already present it returns False and changes nothing.
  • remove(t, id) returns True. If the transaction is missing it returns False and changes nothing.
  • correct(t, id, new_t, new_amount) deletes the old transaction and inserts the corrected one. It never edits a key or an amount in place. A missing transaction raises KeyError and changes nothing.
  • balance(t) is the sum of every amount at or before time t. total_between(t1, t2) covers t1 <= timestamp <= t2, with both bounds inclusive, and is 0 when t1 > t2. Both are 0 on an empty ledger.
  • kth(k) is the k-th transaction in time order, 1-based, as (t, id, amount). It raises IndexError for k outside 1..n, including any k on an empty ledger.
  • rebalance() rebuilds the tree to height ceil(log2(n + 1)). Only the program calls it. No insert or delete rebalances by itself.

The kit's search, size_of, select, sizes_ok, is_bst and height are given in the answer, and they work on the new node class unchanged.

  1. Write the node class, total_of, a checker sums_ok, and an insert and a delete that keep size and total right on the way down. In the two-child delete, the successor's amount leaves every subtree between the deleted node and the successor. Then write the Ledger class. Trace five transactions, two of them late. Show a duplicate add, a missing remove, a correction and the empty ledger.
  2. Load 3,000 transactions whose timestamps are 0..2,999, each arriving at most about 10 places late. Print the height (in nodes) beside log2(n). Call rebalance() and print the height again, asserting it equals ceil(log2(n + 1)).
  3. Write the oracle: a sorted list of (t, id, amount) with a prefix-sum array rebuilt after every change (DSA Topic 6). Run 200 seeded scripts of 40 operations each. Every 10th script adds strictly in time order. Mix adds (some late, some duplicates), removes (some missing), corrections, rebalances and queries. After every operation compare the answers, the in-order list, is_bst, sizes_ok and sums_ok. Count an exception as a failure. Count and assert the empty ledger, a single transaction, the sorted scripts, late arrivals, missing removes, duplicates and rebalances.
  4. Say what Python code would use instead and when you would still write the tree. State time and space for every function, with h named.
Q92The Secondary IndexMini-Project

Records (name, age) live in a dict keyed by id (DSA Topic 7). Ids are distinct ints >= 0 and ages are ints. Build a secondary index on age: a size tree (a binary search tree whose nodes store size, the number of nodes in their subtree) keyed by the tuple (age, id). The tuple keeps the keys distinct even when ages repeat. DSA Topic 7's "designing for queries" kept a dict and a sorted list together. The tree is the version whose updates stay O(h).

The empty index is the tree None. The class People must keep these contracts:

  • add(id, name, age) stores and indexes a record. A duplicate id raises ValueError and changes nothing.
  • remove(id) returns True. A missing id returns False and changes nothing.
  • set_age(id, age) deletes the old index key and inserts the new one, never editing a key in place. A missing id raises KeyError and changes nothing. The same age changes nothing.
  • aged_between(lo, hi) returns the ids with lo <= age <= hi, both inclusive, in (age, id) order, in O(h + k). It returns [] when lo > hi or the index is empty.
  • count_aged(lo, hi) is the size of that band in O(h), from two rank walks, and 0 when lo > hi.
  • oldest(k) returns the k ids that are largest in (age, id) order, largest first. It returns every id when k > n and [] when k <= 0.

The kit's search, SizeNode, size_of, size_insert, size_delete, rank, sizes_ok, is_bst, in_list and height are given in the answer.

  1. Write People and a consistency checker. The index's in-order list must equal the sorted (age, id) pairs of the dict, and is_bst and sizes_ok must both hold. Trace six records, an age change, a duplicate id, missing ids, the empty index and lo > hi.
  2. Run 500 seeded scripts of 30 operations each. Compare every query with a scan of the dict, and run the consistency checker after every operation. Every 10th script adds in increasing age order, which makes the index a path. Count an exception as a failure. Count and assert the empty index, a single record, the sorted scripts, duplicate ids, missing ids, unchanged ages and two-child deletes.
  3. At 10,000 records, count the nodes one band query visits and assert that they stay within k + 2h. Then make 1,000 age changes. Count the entries a sorted list of (age, id) would shift, against the nodes the tree's delete and insert touch. Say what the shift costs in CPython, and when the tree is the right choice. State time and space for every function, with h named.
Q93The Price AlertsMini-Project

Users set price alerts at integer thresholds. Store them in a binary search tree keyed by (threshold, alert id), so equal thresholds stay distinct keys, and keep a dict from id to threshold so an alert can be cancelled. The empty book is the tree None. An alert fires as a range, and the range can run in either direction. The book never repeatedly takes out the smallest key.

The contracts:

  • add(id, threshold): a duplicate id raises ValueError and changes nothing. An alert at exactly the current price does not fire now. It fires on a later move that reaches its threshold.
  • cancel(id) returns True. A missing id returns False and changes nothing.
  • move(q): the price moves from p to q. If q > p, every alert with p < threshold <= q fires. If q < p, every alert with q <= threshold < p fires. If q == p, nothing fires. So a threshold equal to p never fires on this move, because the price starts there, and a threshold equal to q always does. Fired alerts are removed and returned in (threshold, id) order, whichever way the price moved. Moving on an empty book returns [].
  • nearest() returns (below, above). below is the largest key whose threshold is <= the price, and above is the smallest key whose threshold is >= the price. Either is None when no alert qualifies.

The kit's TreeNode, in_list, insert, delete, is_bst and height are given in the answer.

  1. Write cut(lo, hi), which removes every key with lo <= threshold <= hi in one pass, in O(h + k) for k fired alerts. The range delete from earlier in this topic recursed. This one is a loop, so a path of alerts cannot run out of stack:

    1. Walk down to X, the first node whose threshold is in range.
    2. In X's left subtree, a node at or above lo is fired together with its whole right subtree, and the walk continues left. A node below lo is kept, and the walk continues right, relinking past the fired nodes. Do the mirror image in X's right subtree.
    3. Join the two kept parts in X's place, under the smallest kept key above the range.

    Count every node touched in self.work. Nothing in this question is timed.

  2. Write the Alerts class on top of cut. Trace seven alerts, including an alert at the start price, one at the end price, equal thresholds, a move of zero, a cancel twice, a duplicate id and an empty book.

  3. Run 200 small seeded scripts against a scan of every alert, checking the in-order list and is_bst after every operation. Every 10th script sets thresholds in increasing order, which builds a path. Count an exception as a failure. Count and assert the empty book, a single alert, the sorted scripts, thresholds equal to p and to q, and moves up, down and of zero.

  4. Run 10,000 seeded ticks over about 2,000 standing alerts. Fired alerts are replaced by new ones near the new price. Check every tick against the scan. On every 10th tick, measure the height first and assert that the work stays within k + 3h. Print the nodes touched per tick by the tree and by the scan, and the final height beside 2.5 * log2(n).

  5. Say what Python code would try first, and state time and space for every function, with h named.

Q94The Interval IndexMini-Project

Build an interval index. Closed intervals [start, end] of ints with distinct int ids are stored in a binary search tree keyed by (start, id). Each node also stores maxend, the largest end anywhere in its subtree, itself included. That one augmented field lets a query skip whole subtrees:

  • Skip a subtree whose maxend is below x. No interval in it reaches x.
  • Skip a right subtree once a node's start passes x. Every start in it is larger still.

The empty index is the tree None. The class Intervals must keep these contracts:

  • add(id, start, end): a duplicate id, or start > end, raises ValueError and changes nothing.
  • remove(id) returns True. A missing id returns False and changes nothing.
  • stab(x) returns the sorted ids of every interval with start <= x <= end. An interval that only touches x at an end counts.
  • overlapping(a, b) returns the sorted ids of every interval that meets [a, b], that is start <= b and end >= a.
  • rebuild() rebuilds the tree balanced and recomputes every maxend. Only the program calls it. No insert or delete rebalances, and nothing rotates.

The kit's search, is_bst and height are given in the answer.

  1. Write the node class and a checker maxend_ok. Write the insert, which raises maxend on the way down. Write the delete, which records its path, including the walk to the successor in the two-child case, and recomputes maxend bottom-up along that path. It cannot be fixed on the way down, because the interval leaving may hold the largest end. Trace seven intervals, a removal that changes a maxend, a missing id, a bad interval and the empty index.
  2. Run 200 seeded scripts of 40 operations each. Compare every stab and overlapping with a scan of every interval, and check the order, every maxend and the dict after every operation. Every 10th script adds starts in increasing order. Count an exception as a failure. Count and assert the empty index, a single interval, the sorted scripts, two-child deletes, missing ids, point intervals (start == end) and queries that touch an interval exactly at its end.
  3. Store 10,000 seeded intervals and stab 1,000 seeded points. Check 200 of the stabs against the scan. Print the average and worst number of nodes visited beside n, and the height in nodes.
  4. Add 2,000 intervals in start order. Print the height and the visits for one stab near the end. Call rebuild() and print both again.
  5. Say what Python code would do instead, and state time and space for every function, with h named.
Q95The Word ConcordanceMini-Project

A concordance lists every word of a text with where it appears. Build one as a binary search tree keyed by the word. Strings compare whole, alphabetically ("cat" < "dog"), and nothing branches letter by letter. Each node holds:

  • count, how many times the word occurs;
  • lines, the sorted line numbers it occurs on, each line listed once, with lines numbered from 1;
  • size, the number of words in its subtree, so the kit's select and rank work on it unchanged.

Words are the runs of letters a–z, lowercased. Find them with a character loop (and str.split for lines), not re. The empty concordance is the tree None. The contracts:

  • entries() returns (word, count, lines) for every word, alphabetically.
  • between(w1, w2) returns the words with w1 <= word <= w2, alphabetically, in O(h + k). It returns [] when w1 > w2.
  • select(root, k) gives the k-th word alphabetically (1-based). rank(root, word) counts the words alphabetically before word, whether or not it is present.
  • neighbours(word) returns the largest word before word and the smallest after it. The word need not be in the text and is never returned itself. A side with no word is None.
  • most_frequent(m) returns the m most frequent words as (word, count), sorted by (-count, word), so ties go alphabetically.
  • Adding a word that is already present raises its count and adds its line once, and changes no size.

The kit's search, size_of, select, rank, sizes_ok, is_bst and height are given in the answer.

  1. Write the node class, tokenize, add_word and the Concordance class. Print the concordance of a three-line text, a range, the 3rd word, a rank, the neighbours of a missing word and of a word past the end, the top three and a reversed range.
  2. Check every query against a dict of word -> [count, lines] built with str.split plus sorted(). Use an empty text, a one-word text, a text whose words already arrive alphabetically, and three seeded texts of made-up words. Every k and the rank of every word, plus 300 probes per seeded text: present words, words just beside them, and words before and after all of them. Count an exception as a failure, and assert that each kind of text was checked.
  3. For each seeded text, print the height in text order beside the number of distinct words. Then feed the same words alphabetically and print the height again. Assert that it is a path.
  4. Say what Python code would use instead and when you would still write the tree. Prefix queries belong to a different structure (named only). State time and space for every function, with h named.
Q96Explaining It ColdInterview

An interviewer says: "Tell me about binary search trees." Give the explanation as ten short points. Back each one with a line or two printed by code, using the kit (given in the answer) and the standard example T10, the tree built by inserting 41, 20, 65, 11, 29, 50, 91, 32, 72, 99. Say each point in plain words:

  1. The property: every key in a node's left subtree is smaller and every key in its right subtree is larger. Explain why that makes the in-order list sorted.
  2. Search and insert walk one path from the root, so they are O(h). Print the keys a search visits for a present key and for a missing one.
  3. The three cases of delete: a leaf, one child, two children. Delete one of each from T10 and print the tree by level after each.
  4. The parent-check trap: on [10, 5, 15, None, None, 6, 20], every parent-child pair is in order, but the tree is not a search tree.
  5. The successor (the smallest key greater than x), and the k-th smallest and the rank from stored subtree sizes.
  6. The height (in nodes) depends on the insertion order. Measure five random orders of 10,000 keys against log2(n) and 2.5 * log2(n), and 1,000 keys inserted in sorted order.
  7. Why stored sizes make select and rank O(h). Print the sizes select reads at the root, and the move it makes.
  8. A rotation changes the shape and never the in-order list.
  9. The AVL and red-black invariants, each checked on an example, and the heights they promise at 100,000 keys beside a perfect tree, a random order and a sorted order. Find the tallest AVL tree from the fewest nodes an AVL tree of each height can have. These trees are explained here, not built.
  10. When a dict, a set or a sorted list is the better choice. Time 10,000 exact lookups in the tree against a set (min of 3) and take the verdict by the 2x rule: 2x or more either way, else "no verdict: within 2x".

State time and space for every function, with h named.

Q97Diagnosing By ReasoningInterview

An interviewer hands you five search-tree functions, each with one bug. For each one, predict the smallest input that fails, and why, before running anything. Write the predictions into the code as data: the size of the smallest failing tree and a sentence of reasons.

  1. A validator that compares each node with its children and its grandchildren, and nothing further down.
  2. A k-th smallest that counts nodes in pre-order (node, left, right) instead of in-order.
  3. A recursive delete whose two-child case copies the successor's key into the node and then deletes x again from the right subtree, instead of the successor's key.
  4. A closed range count, the number of keys with lo <= key <= hi, written rank(hi) - rank(lo), where rank(x) counts the keys below x.
  5. A search that tests x <= node.val (go left) before it tests equality.

Then confirm each prediction with a scan in increasing size. For the validator, scan every shape with up to five nodes labelled with every permutation of its keys (5,412 trees, judged by the brute-force property check). For the other four, scan every search tree with up to seven keys (ALL_BST, 626 trees), with every k, every present key, or every lo <= hi as the bug needs. A delete runs on a fresh copy each time. Print the prediction beside the size found, the smallest failing input, and the buggy answer beside the right one. Assert each prediction.

Finally, check each fix against an oracle that works differently. Use is_bst against the brute-force property on the 5,412 labelled trees. On all 626 search trees, check the in-order k-th, the kit's search, rank(hi + 1) - rank(lo) and the fixed delete against the sorted key list. The kit pieces are given in the answer. State time and space for every function, with h named.

Q98Designing For OperationsInterview

An interviewer gives you three APIs as complexity targets on a changing set of distinct integer keys, with inserts and deletes arriving at any time. Design all three on one augmented node class: a binary search tree node that stores size (the nodes in its subtree) and total (the sum of its subtree's keys). Say why each meets its target.

  1. median() in O(h): the lower median, select at (n + 1) // 2, or None for an empty set. DSA Topic 5 kept a sorted window with bisect for a sliding median. Here the set changes anywhere, and no second structure is kept.
  2. sum_smallest(k) in O(h): the sum of the k smallest keys, for 0 <= k <= n, else IndexError. Use one walk: going right past a node adds its left subtree's total and its own key.
  3. count_within(x, d) in O(h): how many keys lie in [x - d, x + d], from two rank walks. d < 0 raises ValueError.

Write the node class, an insert and a delete that keep both fields right, and a checker for the totals. The kit's search, SizeNode, size_of, select, rank, sizes_ok, is_bst and height are given in the answer. Each query returns its answer and the nodes it visited. The counted copies of select and rank are checked equal to the kit's.

Then:

  1. Show the three APIs on T10's keys (41, 20, 65, 11, 29, 50, 91, 32, 72, 99), before and after a delete, and on an empty tree.
  2. Run 300 seeded scripts against a sorted list (bisect). Every 10th script inserts in increasing order. Check is_bst, sizes and totals after every operation. Assert that the visits stay within h, h and 2h (height in nodes), and print the largest visits / bound seen. Count an exception as a failure. Count and assert the empty set, a single key, the sorted scripts, even n, k = n, d = 0 and a rejected k.
  3. The trade: count the augmented-field writes per insert over 10,000 random inserts, and print the bytes per node object (sys.getsizeof) for a plain node, a size node and this node. Say what rotations in a self-balancing tree would add.

State time and space for every function, with h named.

Q99The Mock InterviewInterview

Mock interview. "Given a binary search tree of distinct integer keys, a target and k, return the k keys closest to the target, nearest first. When two keys are equally near, the smaller key wins. If k is larger than n, return every key."

  1. The first answer: list the keys in-order, bisect for the target, and expand two pointers outward (DSA Topic 3's k closest, cited). Say why it is O(n) whatever k is.
  2. The better answer, O(h + k). One walk down from the root fills two stacks: the predecessor path (nodes with keys below the target) and the successor path (keys at or above it). Each step pops the nearer top and moves that stack one key outward, using a left spine or a right spine. Ties go to the predecessor. The two-sum question earlier in this topic started its two stack iterators at the ends. Here both start at the target.
  3. Fuzz the two stacks against the first answer and against sorting every key by (distance, key). Use every tree of ALL_BST with every target and every k, plus 200 seeded trees of 0 to 300 keys. Every 10th seeded tree is built from sorted keys, which makes a path. Assert that the nodes pushed stay within 2h + k (h the height in nodes). Count an exception as a failure. Count and assert the empty tree, a single key, the sorted trees, ties, k > n and k = 0.
  4. With a counted copy (never timed), print the most nodes pushed in 200 queries with k = 10 beside the asserted bound 2h + k, at n = 10^3, 10^4 and 10^5.
  5. Time both plain answers on 100 queries at n = 10^4 (min of 3). Give the verdict by the 2x rule: 2x or more either way, else "no verdict: within 2x".
  6. Follow-ups:
    • On a path the walk down alone is O(n). Count it.
    • With many queries on a set that does not change, sort once and use the list. Time k = 1 and k = 10, ratio only, because both ratios move under load.
    • Show that k larger than n returns every key.

State time and space for every function, with h named.

Q100CapstoneInterviewMust Do

Build a departures index for one airport day.

The data. A flight is a record (time, flight, gate). The time is an int number of minutes after midnight, and a delay may push it past 1439. The flight is a non-empty string, distinct across the day, such as "JC0042". The gate is a string. Records are keyed by the tuple (time, flight), so two flights leaving at the same minute are still distinct keys and sort by flight.

The structure. A binary search tree stores distinct keys so that every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. Its in-order list (left subtree, node, right subtree) is therefore sorted. Each node here also stores size, the number of nodes in its subtree, itself included. That turns two questions into one walk from the root each, O(h), where h is the height, the number of nodes on the longest root-to-leaf path:

  • select(k) returns the k-th smallest key, with k = 1 the smallest. At each node, compare k with the left subtree's size: go left, stop here, or subtract and go right.
  • rank(x) counts the keys smaller than x. Every right turn adds the left subtree's size plus one.

A dict from flight to (time, gate) finds a flight's key and gate. The empty index is the tree None. These helpers were written earlier in this topic and are pasted in the answer:

  • search(root, x) returns the node holding x, or None.
  • SizeNode is a node with val, left, right and size. size_of(node) returns its size, or 0 for None.
  • size_insert(root, x) and size_delete(root, x) keep every size right on the way down and return the root. A present key on insert, or a missing key on delete, changes nothing.
  • select(root, k) and rank(root, x) work as above.
  • sizes_ok(root) checks that every size equals 1 plus its children's sizes.
  • is_bst(root) checks that every key lies strictly between the bounds its ancestors set.
  • height(root) counts nodes, with the empty tree 0.
  • best_of(fn) returns the smallest wall time of 3 runs.

The contracts.

  • bulk_load(records) builds an empty index as a balanced tree, with the middle key at the root, recursively, so its height is ceil(log2(n + 1)). A non-empty index or a repeated flight raises ValueError, and nothing is loaded.
  • add(time, flight, gate): a flight already present raises ValueError and changes nothing.
  • cancel(flight) deletes the flight and returns True. A missing flight returns False and changes nothing.
  • delay(flight, minutes) is a delete followed by an insert. A key is never edited in place, because that would break the order. A missing flight raises KeyError, minutes < 0 raises ValueError, and either way nothing changes.
  • next_departure(t) returns the first departure at or after time t (the ceiling on time) as (time, flight, gate), or None.
  • between(t1, t2) returns every departure with t1 <= time <= t2, both inclusive, in key order. It returns [] when t1 > t2.
  • kth(k) returns the k-th departure of the day, 1-based. k outside 1..n raises IndexError.
  • count_before(t) is how many departures leave before time t.
  • rebalance() rebuilds the tree balanced. Only the program calls it. No insert or delete rebalances by itself.
  • validate() is True when the tree is a search tree, every size is right, and the tree and the dict hold the same keys.

The steps.

  1. Trace a five-flight day: a ceiling, a range with two flights at the same minute, a k-th, a count, a missing cancel, a delay, and the four refused calls. Then run an empty day.
  2. Seed a full day. Bulk-load 300 morning flights. Then add 400 afternoon flights in time order, with a few queries between them. Print the height before and after one call to rebalance(). Then run 300 mixed changes (delays, cancels, some of missing flights, and adds) and queries. Run validate() after every step, and check every query against a brute force that scans the flat records with no tree and no bisect.
  3. Run the same day on a sorted list of (time, flight) tuples with bisect and the same dict. Assert that both give the same answers. Time both on plain code, with no checks (min of 3). Time the whole day, then the two phases separately, with each phase's starting index built outside the timer: the afternoon's adds, then the changes and queries after rebalance(). Give verdicts by the 2x rule (2x or more either way, else "no verdict: within 2x") on the whole day and the afternoon. Print the post-rebalance phase as a ratio only, because it moves under load.
  4. Fuzz 200 seeded days against the brute force: empty and one-flight mornings, afternoons in time order and shuffled, and missing cancels. Count an exception as a failure, and count and assert each case.
  5. Close with a recommendation, a line on why (both phases, and the afternoon's share of the tree's time), and a line about the shape, all built from the computed verdicts, ratios and heights, never typed.

State time and space for every method, with h named: ceil(log2(n + 1)) after a bulk load or a rebalance, about 2.5 * log2(n) for adds in random time order, and up to n for adds in time order.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session