Data Structures & Algorithms practice
Data Structures & Algorithms ยท Hierarchical Structures

Tries: 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 Prefix TreeEasyMust Do

A trie (say "try", a prefix tree) stores a set of strings as a tree. The root is the node for the empty string "". Every other node hangs below its parent on one edge that carries one character, so the path from the root to a node spells a prefix, and two words that begin the same way share the start of their path. The words stored are the ones whose path ends at a node marked as a word. Before any class exists, find out how many nodes a trie needs: one for each distinct prefix of each stored word, "" and the whole word included.

  1. Write out LETTERS (the 26 lowercase letters) and WORDS (24 short words, written in the answer, several of them prefixes of others such as "a", "an", "and").
  2. Write prefixes_of(words): a set of every prefix of every word in words, "" and each whole word included.
  3. For WORDS, print the number of words, their total characters, and the number of nodes (one per distinct prefix, and the root for ""). Then print the prefixes grouped by length, one line per length with how many there are.
  4. Assert nodes <= characters + 1 on WORDS, on ["a", "ab", "abc"] (4 nodes for 6 characters, since each word starts with the one before it), on ["ab", "cd"] (nothing shared), on [] and on [""]. The bound holds by construction: the root, plus at most one new node per character.
  5. Print how many nodes one separate path per word would need, against how many the shared paths need, and the difference.
Q2A Node As A Dict Of ChildrenEasyMust Do

A trie node needs two things: a way to find the child for each next character, and a flag saying whether a stored word ends here. Use a dict for the first: children maps one character to the child node below it, so finding the child for a character is one dict lookup, which costs O(1) on average whatever the alphabet (DSA Topic 7), and only the children that exist take any space. The flag is end, True when a word ends at this node. A node does not store its own character: the key of the edge into it does.

  1. Write TrieNode with __slots__ = ("children", "end"), an empty children dict and end = False.
  2. Write link_word(root, word): walk word from root one character at a time, creating a missing child with a new TrieNode, and set end = True on the last node. (No trie class yet: this is a plain function.)
  3. Write outline(node), which returns the trie below node as text lines in alphabetical order: one line per node, two spaces of indent per level, the node's character, then " *" when a word ends there. It is iterative, with an explicit stack, and sorts each node's child keys so the order never depends on insertion order.
  4. Link "car", "card", "care", "cart" and "cat" by hand into one root and print the outline. Assert that it has one line per distinct non-empty prefix of the five words.
  5. Print the keys of the dict at the root, at the node for "ca" and at the node for "car", with each node's end flag, and assert that a TrieNode has only the two slots (no character).
  6. Walk "cart" from the root, counting the dict lookups: one per character. Then print how many dict entries the trie holds, against the slots that a 26-slot array per node would hold (the real bytes of both are measured later in this topic).
Q3Insert, One Character At A TimeEasyMust Do

Now put the walk inside a class. A Trie keeps a root (a TrieNode: a children dict from one character to a child node, and an end flag that is True when a word ends there) and size, the number of distinct words stored. Any string may be stored, "" included (it marks the root). insert(word) walks the word from the root one character at a time, makes the child when it is missing, and sets end on the last node. It returns True if the word was new and False if it was already stored. len(trie) is the number of distinct words stored. Helpers written out in the answer: outline(node) (the trie below node as indented lines, one per node, alphabetical, a " *" after each word end, iterative), count_nodes(node) (how many nodes at and below node, iterative), and the three test beds STRS (the 15 strings of length 0 to 3 over "ab"), BED (every list of 0 to 3 of those strings in every order, repeats allowed) and PROBES (the 40 strings of length 0 to 3 over "abc").

  1. Write TrieNode and Trie with __init__(words=()), __len__ and insert.
  2. Trace insert on "car", "card" and "cat": after each, print what it returned, len and the node count, then the outline.
  3. Build the three beds (assert their sizes by construction: 15, 3,616 and 40).
  4. On every list of BED, insert the words one by one and assert that each call returns True exactly when the word was not seen before in that list, that count_nodes(root) equals the number of distinct prefixes (the root counted), and that len(trie) equals the number of distinct words.
  5. Show a broken insert that always makes a new child (node.children[ch] = TrieNode()) and so throws away what hung below. Find, by scanning BED in order, the first list where its len is wrong, and the first list where len is right but the outline is wrong, and print each beside the truth.
Q4Search And starts_withEasyMust Do

A trie answers two different questions, and they are not the same. search(word) is True only when word itself was stored. starts_with(prefix) is True when some stored word begins with prefix, and a stored word equal to prefix counts. For the empty prefix "", starts_with("") is True exactly when at least one word is stored (so False on an empty trie), and search("") is True only when "" itself was stored. Both start with one shared walk, _walk(s): follow the characters of s from the root and return the node reached, or None where the path breaks. The trie is a TrieNode (a children dict from one character to a child, and an end flag that is True where a word ends) under a root, with insert returning True for a new word, and the test beds STRS, BED and PROBES (written out in the answer: the 15 strings of length 0 to 3 over "ab"; every list of 0 to 3 of them, repeats allowed, 3,616 lists; and the 40 strings of length 0 to 3 over "abc").

  1. Write the TrieNode, Trie (with __init__, __len__, insert, _walk, search and starts_with) and the beds.
  2. Write the brute-force oracle ScanWords: a Python set of the stored words, where search is word in set and starts_with scans every stored word with str.startswith.
  3. On every list of BED and every probe of PROBES, assert that search and starts_with of the trie equal those of ScanWords, and that when _walk returns None both answers are False. Count the probe checks: 3,616 lists times 40 probes, by construction.
  4. Show a broken starts_with that returns node.end (it only accepts a prefix that is itself a word). Scan BED in order, each list with every probe in order, for the first failing pair, print it beside the truth, and count the failing pairs.
  5. Print starts_with and search for "ap", "app" and "apple" on a trie holding "apple".
Q5The End-Of-Word MarkerEasyMust Do

Reaching a node is not finding a word. A trie holding "apple" has a node on the path for "app", but "app" was never stored. That is why every node carries an end flag, True only where a stored word ends, and why search(word) must check it. A trie here is a TrieNode (a children dict from one character to a child node, and the end flag) under a root; insert(word) walks the word from the root, creating missing children, and sets end on the last node; _walk(s) follows the characters of s from the root and returns the node reached, or None where the path breaks. Correct search(word) is _walk(word) reaching a node whose end is True. For the empty word, search("") is True only when "" was stored. The test beds are STRS (the 15 strings of length 0 to 3 over "ab"), BED (every list of 0 to 3 of them, repeats allowed, 3,616 lists) and PROBES (the 40 strings of length 0 to 3 over "abc"), written out in the answer.

  1. Write TrieNode, Trie (__init__, __len__, insert, _walk, search) and the beds. The oracle for a probe is probe in set(words).
  2. Write two broken subclasses of Trie. The first calls a node a word when it has no children (a leaf is a word). The second calls a node a word when the walk reaches it (a path is a word).
  3. For each, scan BED in order, each list with every probe in order: print the first failing (list, probe) beside the truth, and count the failing pairs and lists.
  4. Show each on ["app", "apple"] for the probes "", "a", "ap", "app", "appl", "apple" and "apples", as a table of truth, leaf-is-word and path-is-word.
  5. Take the 24 words of WORDS (written out: "a", "an", "and", "ant", "any", "app", "apple", "apply", "apt", "bat", "bath", "bathe", "be", "bean", "bear", "beard", "car", "card", "care", "cart", "cat", "do", "dog", "dot"). Count and list the words that end at a node that has children, and assert that the leaf-is-word version misses exactly those. Count the nodes that are on a path but are not words, and assert that the path-is-word version accepts exactly those.
Q6The Empty String And The Empty TrieEasy

Two edge cases hide in every trie. The empty trie has a root and no words. The empty string "" is a legal word, and storing it marks the root as a word end: it adds no node. The contracts: search("") is True only when "" itself was stored; starts_with("") is True exactly when at least one word is stored, of any kind; len counts the distinct words, "" included; the node count includes the root. A trie here is a TrieNode (a children dict and an end flag) under a root, with insert, _walk (the node reached by following a string from the root, or None), search, starts_with and count_nodes (how many nodes at and below a node), all written out in the answer.

  1. Print a table of four cases (the empty trie, a trie of ["a"], of [""] and of ["", "a"]) against search(""), starts_with(""), len and the node count. Assert each cell against the contract.
  2. Assert that storing "" in the trie of ["a"] returns True, changes len by 1 and the node count by 0.
  3. Count the lists of BED (every list of 0 to 3 of the 15 strings of length 0 to 3 over "ab", repeats allowed, in every order) that hold "", and check search and starts_with against a set and str.startswith for every list and every probe of PROBES (the 40 strings of length 0 to 3 over "abc").
  4. A student writes starts_with(p) as _walk(p) is not None. Scan BED and PROBES in order, print the first failing pair beside the truth, and assert that the failing pairs are exactly the empty list with the probe "".
Q7Inserting A Word TwiceEasy

Storing a word that is already stored must change nothing. insert returns False in that case (True when the word is new), and neither len (the number of distinct words) nor the node count moves. A trie here is a TrieNode (a children dict and an end flag) under a root, with insert, __len__ and count_nodes (how many nodes at and below a node) written out in the answer. The reason insert reports newness is that a caller counting distinct words in a stream needs no second lookup.

  1. For every list of BED (every list of 0 to 3 of the 15 strings of length 0 to 3 over "ab", repeats allowed, in every order) that has a repeated word, build the trie, then insert every word again. Assert that every second insert returns False and that len and the node count are unchanged. Print how many such lists there are (660 by construction).
  2. Show a broken insert whose size counter adds 1 on every call. Find, by scanning BED in order, the first list where its len is wrong, print it beside the truth, and assert that the failing lists are exactly the lists with a repeat.
  3. Insert a stream of 36 words (WORDS, written out, then every second word of it again) and count the distinct words using only the return values. Assert that the count equals len and len(set(stream)).
Q8How Far A Miss GetsEasy

A failed search stops at the first character with no child, so a miss often costs far fewer than len(word) lookups. Measure how few. A trie here is a TrieNode (a children dict and an end flag) under a root, with insert and __len__, written out in the answer with random_words(n, rng, alphabet, lo, hi): exactly n random words of lo to hi characters drawn with the seeded generator rng from alphabet, repeats allowed, and a ValueError if n < 0, lo < 0, lo > hi, or the alphabet is empty while hi > 0.

  1. Show the four ValueError cases once, asserting the exception by its type name, and assert that a valid call returns exactly n words.
  2. With random.Random(16), draw 10,000 random words of 3 to 8 letters and 1,000 random probes of exactly 8 letters, and build a trie of the words.
  3. Write a counted walk lookups_for(trie, word) that returns whether the whole path existed and how many dict lookups it made (the failing lookup included). Run it on every probe that is not a stored word, count the lookups with a Counter, print the counts in order and assert that no miss cost more than 8 lookups.
  4. Print the average and the largest number of lookups per miss. A set must hash all 8 letters of a probe before it can look anything up (DSA Topic 7 covers hashing); the timing of the two is measured later in this topic.
Q9A Trie Is An N-ary TreeEasy

A trie is the N-ary tree of DSA Topic 13 with one change: a node keeps its children in a dict keyed by character, where Topic 13's node kept a list. (Its file-system example already noted that a dict of children keyed by name is a trie.) The tree measures carry over, with one change of unit: Topic 13 counted height in nodes (one node has height 1), so the height here, counted in edges, is Topic 13's height minus 1, which is the longest word's length. The height is the depth of the deepest node, and in a trie that is the length of the longest stored word. A node's depth is the length of the prefix it stands for. A leaf here is a node with no children that holds a word, which is a stored word that is not a proper prefix of another stored word. The fan-out is the most children any node has. A trie here is a TrieNode (a children dict and an end flag) under a root, with insert and __len__, written out in the answer; the tests use BED (every list of 0 to 3 of the 15 strings of length 0 to 3 over "ab", repeats allowed, in every order: 3,616 lists).

  1. Write shape(root), iterative with a stack of (node, depth), returning the node count at each depth (index 0 is the root), the leaves, the words ending at nodes that have children, and the fan-out.
  2. Write an oracle oracle_shape(words) from the set of distinct prefixes and the set of distinct words alone.
  3. Assert on every list of BED that the two agree, that the height equals the longest word's length (0 when there is none), and that leaves plus inner words equal len(set(words)).
  4. Print the shape of the trie of WORDS (written out: 24 words such as "a", "an", "and", "bat", "bath", "bathe"). The words that end above other nodes are the ones the end-of-word marker exercise counted; here they are one of the four numbers of the shape.
Q10Every Word In Alphabetical OrderMedium

A trie hands back its words in alphabetical order, with no sort of the words themselves. words_under(node, path, out) (written out in the answer) is a recursive pre-order walk: if a word ends at node, it appends the word "".join(path) to out, then for each child key in sorted order it pushes the character on the shared path list, recurses and pops it. It restores path before it returns. A trie here is a TrieNode (a children dict and an end flag) under a root, with insert and __len__, also written out.

Why pre-order gives sorted order: a word sorts before its own extensions ("a" before "ab"), and the sorted loop visits siblings in order, so every word under the smaller sibling is output first. A dict keeps insertion order, not alphabetical order, so the sorted call is needed.

  1. Insert WORDS (written out: 24 words such as "a", "an", "and", "bat", "bath", "bathe") in a seeded shuffled order into a trie, collect its words with words_under, and assert that the result equals sorted(WORDS).
  2. Write a variant words_under_unsorted that loops over node.children directly. Run both on the words ["pear", "apple", "plum", "peach", "apricot"], print both orders, and assert that they differ.
  3. On every list of BED (every list of 0 to 3 of the 15 strings of length 0 to 3 over "ab", repeats allowed, in every order), assert that words_under equals sorted(set(words)) and that path is empty afterwards.
  4. Show a broken words_under_post that appends the node's word after its children. Scan BED in order, print the first failing list beside the truth, and assert that the failing lists are exactly the lists in which some word is a proper prefix of another.
Q11Deleting A WordMediumMust Do

A trie stores a set of strings as a tree of nodes. Each node has a dict children (one character to the child node below it) and a flag end that is True when a stored word ends at that node. The root stands for the empty string, so "" is a word like any other: it is stored by setting end on the root. Storing a word twice keeps one copy, and len(trie) counts the distinct words stored. A dead node is any node except the root that has no stored word at or below it: it ends no word and leads to none, so it only wastes memory and makes starts_with lie.

Write Trie.delete(word) with this contract:

  • It returns True and removes the word when the word is stored, and False with nothing changed when it is not stored. That includes an empty trie, a path that breaks partway, "" when "" is not stored, and a word that is only a prefix of a stored word (deleting "ap" from {"app"} is False).
  • Words that share the path stay stored: deleting "app" from {"app", "apple"} keeps "apple".
  • It leaves no dead node: afterwards every node except the root leads to a stored word.
  • It is iterative: walk down keeping every node on the path in a list, unmark the end flag, then walk back up from the bottom and cut each node that ends no word and has no children, stopping at the first node that is still needed.

These helpers are written out in the answer: Trie (with insert, search, starts_with), ScanWords (the brute-force oracle: the words in a Python set, every question answered by scanning them with str.startswith), words_under (all stored words below a node, alphabetically), count_nodes (how many nodes at and below a node) and outline (the trie as indented text, a * marking each word end).

  1. Write delete and trace it on ["app", "apple", "apt"]: print outline after each of delete("apple"), delete("ap"), delete("app"), delete("apt"), with each return value.
  2. Check it on every list in BED (3,616 lists of 0 to 3 strings over "a" and "b", repeats and "" included, 15 distinct strings in STRS): build the trie, then delete each of the 15 strings in turn, once in the order of STRS (shortest first) and once in reverse (longest first). After every delete compare with ScanWords: the return value, len, the listing from words_under, no dead node, and count_nodes equal to the number of distinct prefixes of the words left (the root's empty prefix included). Count the kinds of delete that were hit and assert each kind happened.
  3. A student cuts the end node from its parent even when it still has children below (ForgetsChildrenTrie in the code). Find, by a search in increasing size, the smallest list and word where it breaks, and print its result beside the truth.
Q12Dead Branches After A DeleteEasy

The simplest delete for a trie only unmarks the word: find the node, set end = False, subtract 1 from len, and stop. Every node stays where it was. The answer pastes the Trie from earlier in this topic (a dict of children and an end flag per node, delete cutting the nodes that lead to no word) and ScanWords (the words in a set, every prefix question answered by scanning with str.startswith).

  1. Write FlagOnlyTrie, a Trie whose delete only clears the flag and fixes len (named FlagOnlyTrie in the code).
  2. Over every list in BED of at most 2 strings (241 lists over "a" and "b", repeats and "" included), delete each of the 15 strings in STRS from a FlagOnlyTrie and compare search and starts_with on every probe in PROBES with ScanWords. Count how often each of the two disagrees, and print the first list, word deleted and probe where starts_with lies, beside the truth, for the empty probe and for a non-empty probe.
  3. A dead branch also costs memory. Insert 1,000 random words, delete every one of them, and print how many nodes are left in FlagOnlyTrie and in Trie.
Q13Counting Words With A Prefix By WalkingEasy

To count the stored words that start with a prefix, walk down to the prefix's node (as search does) and then count the nodes at and below it whose end flag is True. The Trie from earlier in this topic and ScanWords (the words in a set, every prefix question answered by scanning with str.startswith) are pasted in the answer. count_prefix(prefix) counts a word equal to the prefix, counts all stored words for "", and gives 0 when the walk breaks.

  1. Write count_by_walk(trie, prefix, visits=None) with an explicit stack. visits, if given, is a one-item list that counts the nodes taken off the stack.
  2. Check it against ScanWords.count_prefix on every list in BED (0 to 3 strings over "a" and "b", repeats and "" included) with every probe in PROBES.
  3. State the cost: the walk is O(L) for a prefix of L characters, and the count visits the whole subtree. Build a trie of 10,000 random words over "a" and "b" (8 to 14 letters), and for the prefixes of length 1, 2 and 3 that begin the most words print the nodes visited next to the nodes in the whole trie.
  4. A student counts the nodes under the prefix instead of the words that end there (count_nodes_not_words in the code). Find the smallest list and probe where it differs from the truth.
Q14Prefix Counts Stored In Each NodeMediumMust Do

A trie stores a set of strings as a tree of nodes: each node has a dict children (one character to the child below it) and a flag end that is True when a stored word ends there. The root stands for the empty string, so "" is a word like any other. Storing a word twice keeps one copy. Counting the words that start with a prefix by walking its whole subtree costs as much as the subtree is big. Instead, give every node an int words: the number of stored words that end at that node or anywhere below it. Then the root's words is the number of stored words, and the words that start with a prefix are the words of the prefix's node, found by one walk.

Write CountNode (with children, end, words) and CountTrie with this contract:

  • insert(word) stores the word and adds 1 to words on every node of its path (the root included). It returns True; a word already stored changes nothing and returns False, so it must search first.
  • search(word) is True only for a stored word, not for a mere prefix of one.
  • count_prefix(prefix) returns how many stored words start with prefix: a word equal to the prefix counts, "" counts every stored word, a prefix the walk cannot follow gives 0, and an empty trie gives 0 for everything. It costs one walk: one dict lookup per character of the prefix and nothing for the words below.
  • len(trie) is the number of distinct stored words.

The class is written out in full in the answer, with a delete that keeps the counts right (this question does not exercise it). Also written out: ScanWords (the brute-force oracle: the words in a Python set, every prefix question answered by scanning them with str.startswith).

  1. Write the classes and trace count_prefix on ["app", "apple", "apply", "apt", "bat"] for the prefixes "", "a", "ap", "app", "apple", "b" and "z".
  2. Check count_prefix on every list in BED (3,616 lists of 0 to 3 strings over "a" and "b", repeats and "" included) with every probe in PROBES (the 40 strings of length 0 to 3 over "a", "b" and "c"), against ScanWords. Also check that the lookups made by one count_prefix call equal len(prefix) or fewer, using a copy of the walk that counts them.
  3. A student skips the search in insert and always adds 1 along the path (NoCheckCountTrie in the code). Find, by a search in increasing size, the smallest list where it counts wrongly, and print the result beside the truth.
  4. The extra field is one int in every node. What that costs in bytes is measured later in this topic.
Q15Keeping Counts Right Through DeletesMedium

In the counting trie from earlier in this topic every node has words, the number of stored words that end at that node or anywhere below it. CountTrie.delete(word) must keep that true: it checks that the word is stored first (returning False with nothing changed if not), then walks down subtracting 1 from words on every node of the path (the root included), cutting off the first node whose words reaches 0 together with everything below it (nothing below it can hold a word), and otherwise clears the end flag of the last node. ScanWords (the words in a set, every prefix question answered by scanning with str.startswith) is the oracle.

  1. Paste CountTrie and write recount_ok(trie): for every node, recount the stored words at and below it with an explicit stack and a second pass that adds up children before parents, and compare with the node's words. It must also find no node with words == 0 below the root.
  2. Fuzz 300 seeded scripts of 40 steps each over the alphabet "abc" (words of 0 to 4 letters): insert, delete, and count_prefix queries chosen by the seeded generator, compared with ScanWords. After every step run recount_ok. Count how many of each case the fuzz hit (an empty word, a duplicate insert, a delete of a stored word, a delete of an absent word, a step on an empty trie, a step on a trie holding one word, a delete of a word that is a proper prefix of a stored word, whether or not it is stored itself, and a delete of a stored word that has another stored word as a proper prefix), catch Exception as a failure, and assert every count is above 0. Add two scripted runs: words inserted in sorted order, then deleted in reverse; and in reverse sorted order, then deleted sorted.
  3. A student subtracts 1 along the path before checking that the word is stored (SubtractFirstCountTrie in the code). Find, by a search in increasing size, the smallest list and word where it goes wrong, and print the broken count beside the truth.
Q16Autocomplete: The First k WordsMediumMust Do

A trie stores a set of strings as a tree of nodes: each node has a dict children (one character to the child below it) and a flag end that is True when a stored word ends there. The root stands for the empty string, so "" is a word like any other. Autocomplete returns the stored words that start with a prefix, alphabetically (plain string order, so a word comes before the longer words it begins), and only the first k of them.

Write complete(trie, prefix, k=None) with this contract:

  • the result is a list of stored words that start with prefix (a word equal to prefix is one of them), in alphabetical order, and a word appears once;
  • k=None returns every such word; k <= 0 returns []; k larger than the number of matches returns them all;
  • a prefix the walk cannot follow, or an empty trie, gives []; the prefix "" matches every stored word;
  • it walks down to the prefix's node, then uses an explicit stack (no recursion) and stops as soon as it has k words, so the words it never needed are never reached.

The idea: pop a node, report it if a word ends there, then push its children in reverse sorted order so that the alphabetically smallest child is popped first. A node is popped before its children, so a word comes before the longer words that begin with it.

These helpers are written out in the answer: Trie (with insert and _walk, the walk that returns the node a string leads to or None), ScanWords (the brute-force oracle: the words in a Python set, every question answered by scanning them with str.startswith and sorted), count_nodes (the nodes at and below a node) and syllable_words (a seeded builder of exactly n different made-up words).

  1. Write complete and trace it on ["bat", "bath", "bathe", "be", "bean", "car"] for prefix "ba" with k = None, 2 and 0, and for "x".
  2. Check it on every list in BED (3,616 lists of 0 to 3 strings over "a" and "b", repeats and "" included) with every probe in PROBES (40 strings over "a", "b", "c" of length 0 to 3) and k in None, 0, 1, 2, 5, against ScanWords.complete.
  3. Count the nodes complete pops against the whole subtree below the prefix, on 10,000 random syllable words (2 to 4 syllables of a consonant and a vowel) with k = 10, for the most common prefixes of length 1, 2 and 3. Use a counted copy and check that it returns the same words as complete.
  4. The flat alternative, a sorted list searched with two bisect_left calls (DSA Topic 3's autocomplete), is timed against this later in this topic.
  5. A student pushes the children in sorted order, not reverse (complete_forward in the code). Find the smallest list and prefix where the result is wrong, and print it beside the truth.
Q17Nodes Against CharactersEasy

A trie never needs more than one node per character stored, plus the root, and it needs far fewer when words share prefixes. The answer pastes the Trie and count_nodes from earlier in this topic, and three seeded builders of word lists. Each returns exactly n different words and raises ValueError for a request that cannot be met:

  • distinct_words(n, rng, alphabet, lo, hi): n different random words of lo to hi letters from alphabet;
  • syllable_words(n, rng): n different made-up words of 2 to 4 syllables, each a consonant then a vowel (SYLLABLES has the 60 of them), such as "kabelo";
  • prefixed_words(n, rng, stems, lo, hi): n different words that each start with one of STEMS ("counter", "electro", ...) followed by lo to hi letters.
  1. Write the builders and show each raising ValueError on a bad request (assert the exception's type name).
  2. For each list at n = 1,000 and n = 10,000 (random words of 3 to 10 letters over a to z; syllable words; stem words with 2 to 5 letters after the stem) print N (total characters), the nodes, nodes per character and nodes per word. Assert nodes <= N + 1 (one node per character at most, plus the root).
  3. State from the numbers which list shares most, and whether sharing grows with n.
Q18The Shape Does Not Depend On OrderEasy

A binary search tree built from the same keys has a different shape for different insertion orders (DSA Topic 14: sorted keys made a path). A trie has no such freedom: a node exists exactly when some stored word begins with the characters on the path to it, and that is a fact about the set of words, not the order they arrived in. The answer pastes the Trie from earlier in this topic and outline(node), which lists the trie as text lines in alphabetical order, one line per node, with * marking a word end.

  1. Take the six words ["a", "and", "app", "apple", "bat", "bath"] (some are prefixes of others). For each size k from 1 to 6, insert the first k of them in every order (itertools.permutations) into a new Trie and assert the outline is identical for every order of the same k words. Count the orders tried.
  2. The dicts inside the nodes do remember insertion order, so the raw children of the root are not always in the same order. Count, for k = 6, how many different root orders appeared, and show why outline hides it (it sorts the keys).
Q19The Nested-Dict TrieEasy

A trie needs no node class: a node can be a plain dict mapping one character to the dict below it. The word end is a key that no character can equal: the empty string "". Every character key is a one-character string, so "" cannot collide with one, and it sorts before every one of them, so a sorted walk reports a word before the longer words it begins. A node holding "" is a word end: node[""] = True. The answer pastes Trie (the class version), ScanWords (the words in a set, every prefix question answered by scanning with str.startswith), count_nodes, distinct_words (exactly n different seeded random words), and two timing tools: traced_bytes(build), which returns what build() made and the bytes it still holds, measured with tracemalloc on inputs made beforehand, and best_of(fn), the smallest of three timings.

  1. Write nd_insert, nd_search, nd_starts_with, nd_words(root, prefix) (the stored words that start with prefix, alphabetically, iterative with a stack) and nd_count_prefix. Check them on every list in BED (0 to 3 strings over "a" and "b", repeats and "" included) with every probe in PROBES against ScanWords and against Trie.
  2. For 10,000 distinct random words (3 to 10 letters over a to z) build a Trie and a nested-dict trie and print the bytes each holds, per word and per node. Time both builds with best_of and print the ratio, with no verdict.
  3. A student uses None as the end key (B19 in the code). nd_search still works. Find the smallest list where the alphabetical listing fails and print the exception's type name.
Q20An End Marker That CollidesEasy

In a nested-dict trie (a node is a dict from one character to the dict below it) a word end needs a mark inside the node. If the mark is a key, it must be a key that no character can be. A student picks "$", a character that never appears in the test words. Then the word "$" itself is stored. The answer pastes Trie (the class version, with a separate end flag in each node, outside the children dict) and ScanWords (the words in a set, every prefix question answered by scanning with str.startswith).

  1. Write build(words, end), search(root, word, end) and starts_with(root, prefix) for a nested-dict trie whose end key is end (end -> True inside the node), and show B20: with end = "$", find, for the alphabet "a$", the smallest list where search returns a wrong True or False and the smallest where it raises an exception, and print each beside the truth (name an exception by its type).
  2. Compare four designs on every list of 0 to 3 strings over "a" and "$" (strings of 0 to 2 characters, repeats and "" included) with every probe of 0 to 2 characters over "a" and "$": the class trie with its separate flag; nested dicts with end key "$"; nested dicts with end key ""; nested dicts with a sentinel object END = object() as the end key (no string equals it). Print a table of how many lists each gets wrong (any probe), and its smallest wrong list.
  3. The sentinel cannot be sorted together with strings (it is not a string). Show that the sorted listing of a node needs the sentinel taken out first (sorted(k for k in node if k is not END)), and say from the table why the class trie needs none of this.
Q21Children: A Dict Or An Array Of 26Medium

A trie node can keep its children in a dict, as every trie so far has, or in a list of 26 slots, one per letter, where the child for ch sits at index ord(ch) - 97. The array looks faster and leaner: no hashing, no keys. Build it and measure the memory before believing that.

  1. Write ArrayNode (a list slots of 26 None entries and an end flag) and slot(ch), which returns ord(ch) - 97 and raises ValueError for anything but a lowercase letter. Write array_insert, array_search and array_starts_with on top of them. Check them against the dict trie on every list of up to three strings over "a" and "b" (3,616 lists, repeats and the empty string included) with each of 40 short probe strings.
  2. Measure bytes per node, structure only (build the words first, then measure the build with tracemalloc), for the dict trie and the array trie on 10,000 random words of 3 to 10 letters and on all 26^3 three-letter words. Print the ratio and how many nodes are leaves. Conclude from the printed numbers.
  3. Show the student bug: no range check, so slot is just ord(ch) - 97. Find by a scan of the printable ASCII characters which stored character makes a lowercase letter wrongly "found", and which one raises an error. Try "Z" and "A" as well.
Q22Recursive Insert And SearchEasy

A trie walk is a loop, but it is also the pass-down recursion of DSA Topic 8: the call for word[i:] hands the child and i + 1 down, and the answer comes back up. Write both walks that way and check them against the loop.

  1. Write rinsert(node, word, i=0), which returns True if the word was new and False if it was already stored, and rsearch(node, word, i=0, calls=None), which counts its calls in the one-item list calls when one is given. Trace four inserts, then check both against the iterative trie on every list of up to three strings over "a" and "b" (3,616 lists) with each of 40 short probe strings: same return values, same outline, same answers, and never more than len(probe) + 1 calls.
  2. State the depth: one frame per character. Print the calls for words of 5, 50 and 500 letters and whether each fits under the recursion limit.
  3. Show the student bug of rsearch that calls itself but does not return the answer. Find the smallest failing list and probe by a scan, and print it beside the truth.
Q23A Trie Of Reversed WordsEasy

A trie answers "starts with" because words that share a start share a path. For "ends with", store each word backwards: the shared ends become shared starts.

  1. Write build_reversed(words) (a trie of every word written backwards), ends_with(rtrie, suffix) (reverse the suffix, then ask starts_with) and words_ending(rtrie, suffix) (the stored words with that ending, alphabetically, turned back the right way round). Check both on every list of up to three strings over "a" and "b" (3,616 lists) with each of 40 short probe strings, against str.endswith on every distinct word. The empty suffix ends every word.
  2. On the 24 words of WORDS, print the node count of the forward trie and of the reversed one (asserted equal to the number of distinct suffixes, empty one included), and the words ending in "t", "e" and "d".
  3. Show the student bug: the trie is built backwards but the query is not reversed. Find the smallest failing list and suffix by a scan, and print it beside the truth.
Q24Nodes Per LevelMedium

A trie's nodes are the distinct prefixes of its words, so the nodes at depth d are the distinct prefixes of length d. Count them level by level to see the shape: where the trie spreads out and where it thins into single chains.

  1. Write nodes_per_level(trie) that returns a list whose entry d is the number of nodes at depth d (the root is depth 0). Walk one level at a time with a deque (DSA Topic 11's queue, as DSA Topic 13's level-order walk does), and write an oracle that counts the distinct prefixes of each length with a set. Check them on the 24 words of WORDS (printed by level).
  2. Build 10,000 random words of 3 to 10 letters and 10,000 syllable words (2 to 4 syllables each), print the counts per level beside 26^d, and for each level the next level's count divided by this one's. Assert that each level equals the oracle and never exceeds 26^d.
  3. From the printed numbers only: call a level bushy when the next level has at least 2 nodes per node, and chain-like when it has at most 1. Print the depths of each kind, the widest level, and the share of the nodes that lie below the first chain-like level.
Q25What A Trie Does Not KnowMedium

A trie is built around the start of a word. Questions about the start cost a few lookups; questions about the middle or the end of a word cannot use the shape at all, because no node knows what lies above it or below it except along one path. Measure the difference on 10,000 syllable words (a consonant then a vowel, 2 to 4 times).

  1. Write starts_with_counted(trie, prefix, lookups), which answers like starts_with and adds one to lookups[0] for every dict lookup it makes. Write count_containing(trie, sub, visits), which walks every node and counts the stored words that contain sub anywhere, adding one to visits[0] per node; and any_containing, which does the same walk but stops at the first word that contains sub.
  2. For "ka" (present) and "kk" (a pair that no syllable word can contain), print the answer and the cost of: some word starts with it, some word ends with it (ask a trie of reversed words), some word contains it, and how many words contain it. Check every answer against startswith, endswith and in on the words.
  3. From the printed counts: the most lookups a prefix question needed, the nodes a substring count needed, how soon any_containing stopped when the substring was there and how far it walked when it was not. Then name, in one line each, what answers "ends with", "how many start with" and "contains" cheaply.
Q26The Longest Common PrefixMediumMust Do

A trie stores words as paths from a root. Each node has a dict children (one character to the child below it) and a flag end, True when a stored word ends at that node; the empty string "", if stored, marks the root itself. Storing a word twice keeps one copy. The trie classes and the other helpers this question uses are written out in the answer.

The longest common prefix of a set of words is the longest string that every one of them starts with. For one stored word it is that word, for no stored words it is "", and when "" is stored it is "". A word counts as a prefix of itself, so for "bath" and "bathe" it is "bath".

  1. Write lcp(trie): starting at the root, walk down while the current node ends no word and has exactly one child, and return the characters passed. Try it on a few hand-written lists, the two edge cases (no words, and "" stored) included.
  2. Write two oracles that use no trie: a column scan (position i is kept while every word is longer than i and they all have the same character there) and the common prefix of just the smallest and the largest word in string order (any other word sorts between them, so it shares with both at least what they share with each other). Check the three against each other on every list of up to three strings over "a" and "b" (3,616 lists, repeats and "" included) and on 300 more lists from random.Random(26), each tried in drawn, ascending and descending order. Count the cases hit (empty trie, "" stored, one distinct word, a word that is a prefix of another, duplicates, both sorted orders, a non-empty answer), assert each is above 0, and count a raised exception as a failure.
  3. Show that the walk's length is the prefix's length and not the number of words: print the nodes and the prefix length for 10, 100, 1,000 and 10,000 words that all begin "interstellar".
  4. Show the student bug that follows a lone child without testing end. Find by a scan of those lists in order of length the smallest failing list, and the smallest failing list that does not store "", and print each beside the truth.
Q27Autocomplete Ranked By WeightMediumMust Do

A search box suggests the best words that start with what has been typed. Each stored word has an integer weight (say, how often it was bought). A trie stores the words as paths from a root: each node has a dict children (one character to the child below it) and a flag end, True when a stored word ends there, and the empty string "", if stored, marks the root. The trie class and the helpers this question uses (among them complete(trie, prefix), which returns every stored word that starts with prefix, alphabetically, by walking the subtree below the prefix's node) are written out in the answer.

Write ranked(trie, weight, prefix, k), where weight is a dict from every stored word to its weight. It returns the k stored words that start with prefix (a word equal to prefix counts) with the highest weights, best first. Equal weights go to the word that comes first alphabetically. k <= 0, a prefix that no word starts with and an empty trie all give []; fewer than k matches give all of them; the empty prefix ranks every word.

  1. Collect the words under the prefix with complete, then pick the top k with heapq.nsmallest(k, matches, key=...) (DSA Topic 15), whose key makes the highest weight come first and settles ties by the word. Try it on a small shop (tea, teapot, teacup, team, ten, tent, top) with several prefixes and values of k.
  2. Write an oracle that uses no trie: filter the distinct words with str.startswith, sort them by weight (highest first) and then by word, and cut at k. Check ranked against it on every list of up to three strings over "a" and "b" (3,616 lists, repeats and "" included) with seeded weights from 0 to 2 (so ties are common), for 13 short prefixes over "abc" (the empty one and every one of 1 or 2 letters) and k = 0, 1 and 3, and on 200 more seeded lists. Count the cases hit (empty trie, "" stored, a word that is a prefix of another, duplicates, a tie inside an answer, k above the matches, an absent prefix), assert each is above 0, and count an exception as a failure.
  3. Print the cost on 10,000 syllable words (a consonant then a vowel, 2 to 4 times) with weights from 1 to 50: for the prefixes "k", "ka" and "kak" and k = 5, the nodes under the prefix (which complete visits all of, by construction), the words collected and the words returned. Say in one line what would avoid the collection.
  4. Show the student bug that ranks by weight only and lets equal weights keep the order a walk met them (children taken in insertion order, not sorted). Find by a scan of those lists in order of length, with equal weights everywhere, the smallest failing list, prefix and k, and print it beside the truth.
Q28Word Search For One WordMedium

A board is a list of rows, each a list of one-character strings. A word is on the board when some path spells it: the path starts at any cell, each next cell is directly up, down, left or right of the one before (no diagonals), and no cell is used twice. The empty word is never found. The search is a recursion like DSA Topic 8's permutation generator: mark a choice used, recurse, then unmark it so the next branch starts clean; here the choice is a cell, and the marks live in a used grid that holds the cells of the current path only.

  1. Write random_board(rows, cols, rng, letters) and syllable_board(rows, cols, rng) (a consonant where row + column is even, a vowel elsewhere, so the board can spell the made-up syllable words later), each exact in size and raising ValueError on a bad request. Write board_words(board, max_len), an oracle that shares no code with the search: the set of every string spelled by a path of 1 to max_len cells, found by trying every ordered choice of cells with itertools.permutations and keeping those whose neighbours touch.
  2. Write board_has(board, word, calls=None), which marks a cell used before it recurses to the four neighbours and unmarks it after, stops a path as soon as a cell holds the wrong letter, and counts its calls in calls when given. Print a seeded 3 x 3 syllable board and the calls for a word on it, a word that is not, and "", each within the bound of 9 starts, 4 first moves and 3 later ones per letter.
  3. Check board_has against board_words on every board up to 2 x 3 over "a" and "b" with every word of 1 to 4 letters, and on 30 seeded 3 x 3 boards over "abc" with every word of 1 to 5 letters. Count found and not found, and assert both are above 0.
  4. Show the student bug that marks a cell used but never unmarks it. Find by a scan (fewest cells first, then the shortest word) the smallest failing board and word, and print it beside the truth.
Q29Many Words, One Search EachEasy

A word game has a dictionary and a board, and wants every dictionary word that is on the board. The simplest plan is one board search per word. Count what that costs before improving it. A word is on the board when a path of neighbouring cells (up, down, left or right, no cell twice) spells it; the helpers syllable_board, syllable_words (n different made-up words of 2 to 4 syllables, each a consonant then a vowel), board_has(board, word, calls) (one search, adding one to calls[0] per call) and the oracle board_words(board, max_len) (every string a path can spell, by itertools.permutations) are written out in the answer.

  1. Write search_each(board, words, calls): the words for which board_has is true, with one shared call counter.
  2. On a seeded 4 x 4 syllable board (print it), run it for 1,000 and for 10,000 syllable words. Print the calls, the calls per word and the words found, and check the words of 4 letters or fewer against board_words.
  3. Measure how much of the work repeats: the number of words whose first syllable an earlier word shared, and the calls spent searching first syllables that had already been searched (search every distinct first syllable once for the cost of one search, and charge each word its own first syllable's cost). Print them, and conclude from the printed numbers.
Q30Word Search With A Trie For PruningHardMust Do

A board is a list of rows, each a list of one-character strings. A word is on the board when some path spells it: the path starts at any cell, each next cell is directly up, down, left or right of the one before (no diagonals), and no cell is used twice. The empty word is never on a board. A trie stores the dictionary as paths from a root: each node has a dict children (one character to the child below it) and a flag end, True when a stored word ends there (a stored "" marks the root and is never found on a board). A call is one call of a search's recursive helper, which enters one cell. A board search marks a cell used when it enters it and unmarks it when it leaves, the way DSA Topic 8's permutation generator marks and unmarks a choice, so the marks always describe the current path. The trie class and the helpers this question uses (syllable_board, a board whose letters alternate consonant and vowel; syllable_words, n different made-up words of 2 to 4 syllables, each a consonant then a vowel; board_has(board, word, calls), one search for one word, adding one to calls[0] per call; board_words(board, max_len), an oracle that spells every path with itertools.permutations) are written out in the answer.

Write find_words(board, trie, calls=None): it returns, sorted, every stored word that is on the board, with one walk from each cell that carries the trie node along. The walk stops as soon as no stored word starts with the letters on the path (the trie prunes); the empty trie gives [].

  1. Check find_words on 30 seeded 3 x 3 boards over "abc" (stored words: 60 sampled words of 1 to 5 letters, plus "" and a repeated word) and on 20 seeded 3 x 3 syllable boards (4-letter words only), against both board_words and one board_has per word.
  2. Count calls three ways on syllable boards of 4 x 4, 5 x 5 and 6 x 6 and dictionaries of 1,000 and 10,000 words: find_words; one board_has per word; and a walk with no trie that extends every path from every cell up to the longest word's length, one call per cell entered (write it as every_path_calls). Assert that the pruned walk never makes more calls than the unpruned one, and check the words found against the per-word search. Print the calls, the words found and both ratios against the trie.
  3. From the printed counts only: on how many rows did the trie make the fewest calls, and what happened to the ratio against the unpruned walk as the dictionary grew ten times. Then print the one-line name for the method: "choosing, recursing and undoing with a test that cuts dead branches is backtracking, DSA Topic 19".
  4. Show the student bug that reports a word only when its node has no children, so a word that is a prefix of another is lost. Find the smallest failing board and stored words by a scan (fewest cells first, stored lists in order of length over "a" and "b") and print it beside the truth.
Q31Edit Distance One, Defined And TestedMedium

A spell-checker needs a precise meaning of "one edit". Here it is: from a string, delete one character, insert one character, replace one character by a different one, or swap two adjacent characters that are different. Nothing else counts, and a string is never one edit from itself. DSA Topic 7's spell checker generated candidates and tested one edit directly against a scan of the vocabulary; this question does not repeat that. Its edits1 also replaced a letter by itself, so it generated 54L + 25 strings with the word among them; this one skips those L, so it generates 53L + 25. It pins down the contract's edges and proves the two ways of asking agree.

The answer pastes two helpers. one_edit(a, b) tests directly, in one scan, whether b is exactly one edit from a. edits1(word, alphabet) returns the set of strings exactly one edit from word, inserting and replacing with characters of alphabet.

  1. Assert the edges: "" against "" is not one edit, "" against "a" is (both ways), equal neighbours such as "aa" have no swap, and a swap of two different letters counts as one edit although it changes two positions.
  2. Check one_edit against edits1 on every pair of strings over "abc" of length 0 to 4. There are 121 strings and so 14,641 pairs (by construction: assert it and say so). For each pair one_edit(a, b) must equal b in edits1(a, "abc"); also count the pairs that are one edit apart and check that one_edit is symmetric.
  3. Check the distinct count by formula. For a word of L >= 1 letters with no two equal neighbours, edits1(word, LETTERS) has 52L + 25 strings, and the empty word has 26. Check it for L = 1 to 9. Build the list of candidates with repeats kept in raw_edits1 and show where the difference comes from. Then show that equal neighbours lower the count.
  4. Show why this question stops at one edit: "ca" is not one edit from "abc", but it is two edits one after the other. (The general edit distance is DSA Topic 21.)
  5. A student counts one edit as "the strings have the same length and exactly one position differs" (B31 in the code). Find the smallest pair where it disagrees with one_edit, with a plain search, and print both answers.
Q32Spell-Check By Walking The TrieHardMust Do

A word list is stored in a trie, and you want every stored word that is exactly one edit from a misspelled word. One edit means: delete one character, insert one character, replace one character by a different one, or swap two adjacent characters that are different. A word is never one edit from itself, so a stored word equal to the query is not returned. The result is a set of strings. The query may be any string, "" included, and it need not be a stored word.

Three functions answer the question, and the answer writes all three. The helpers they call are written out in the answer: Trie (a prefix tree of dict-based nodes; insert stores a word, root is its first node and a node's children maps a character to the child below it and end marks a stored word), edits1(word, alphabet) (the set of strings exactly one edit from word, inserting and replacing with characters from alphabet), one_edit(a, b) (True when b is exactly one edit from a, in one scan), syllable_words(n, rng) (exactly n different made-up words of two to four syllables), and random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words of lo to hi characters, repeats allowed). The bed BED is every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed (3,616 lists), and PROBES is the 40 strings over "abc" of length 0 to 3.

  1. near_by_edits(word, wordset, alphabet): generate every candidate with edits1 and keep the ones in wordset (a set of stored words).
  2. near_by_trie(trie, word, visits=None): walk word down the trie. At each position spend the single edit every possible way (delete word[i]; insert any child's character; replace word[i] by a different child's character; swap word[i] and word[i + 1]), then follow the rest of word exactly. It only ever steps to children that exist, so it never builds a candidate whose prefix is not in the trie. visits, if given, is a one-item list that counts every step from a node to a child.
  3. near_brute(word, words): the oracle, which tests every word of the list with one_edit.
  4. Check that all three agree on every third list of BED with every probe in PROBES, and on 200 seeded random lists (each tried in its given, sorted and reverse-sorted insertion order). Count the cases the checks hit: empty trie, "" stored, a single word, a stored word that is a prefix of another, duplicates.
  5. For 1,000 and 10,000 syllable words, take 300 (respectively 100) stored words, corrupt each with one random edit, and count the steps near_by_trie takes against the distinct candidates edits1 builds. Check every result against near_brute. Decide from the counts, not from a clock, and build the closing line from them.
  6. A student's replace step also allows the same character, which spends no edit (near_by_trie_same_replace in the code). Find the smallest list and probe where it disagrees with near_brute, with a plain search, and print both answers.
Q33The Compressed TrieMediumMust Do

A trie spends one node on every character, even along a stretch where nothing branches: after "bat", "bath" and "bathe" are stored, the nodes for "t", "h" and "e" form a chain. A compressed trie (also called a radix tree) turns every such chain into one edge. Its nodes are RadixNode objects with three fields: label, the string on the edge into the node (the root's is ""); children, a dict from the first character of a child's label to that child; and end, True when a stored word ends at the node. A chain that is folded is a run of trie nodes that each have exactly one child and end no word; a node where a word ends, or that has two or more children, always stays a node of its own.

The answer pastes a Trie (a prefix tree of dict-based nodes: insert, search for a whole stored word, starts_with for a prefix of some stored word, with "" allowed as a word), count_nodes (how many nodes lie at and below a node that has a children dict, iteratively), the list builders (distinct_words: exactly n different random words; syllable_words: exactly n made-up words of two to four syllables; prefixed_words: exactly n words that each start with one of eight long stems and end in 2 to 5 more letters) and the bed BED, every list of 0 to 3 strings over "ab" in every order with repeats and "" allowed (3,616 lists), with PROBES, the 40 strings over "abc" of length 0 to 3.

  1. Write compress(node, label=""), which builds a new radix tree holding the same words as the trie below node and leaves the trie unchanged. It recurses once per radix level, so its depth is at most the longest word. Write radix_search(root, word) (True when word itself is stored) and radix_starts_with(root, prefix) (True when some stored word begins with prefix; the prefix may end partway along an edge; the empty prefix is True exactly when at least one word is stored).
  2. Print a small radix tree with its labels, and show a prefix that ends inside an edge: it is a prefix, but not a stored word.
  3. Check the radix tree against the plain Trie on every list in BED with every probe in PROBES, for search and for starts_with. Check on every list that no non-root node has one child and no word, and that the label lengths add up to the plain node count minus one.
  4. For three lists of 10,000 words (random, syllable, prefixed), print the plain node count, the radix node count and the share of nodes saved. Check 300 stored words and 300 absent probes per list against Trie.
  5. Inserting a word into a radix tree may have to split an edge, and deleting one may merge a lone child back into its parent. Splitting inserts are written later, in a Challenge of this topic. Merging deletes are only named here. This answer builds the radix tree only with compress, from a finished trie.
  6. A student folds a chain even when a word ends inside it, as compress_through_ends in the code. Find the smallest list where it disagrees with Trie, with a plain search, and print both answers.
Q34Memory Per Word: Trie, Set Or Sorted ListMediumMust Do

A trie finds a prefix fast, but how much memory does it cost to hold a word list compared with the two structures Python already has: a set (membership) and a sorted list (prefix ranges with bisect)? Measure it, and let the numbers decide.

What is measured. The word strings are built first, so a structure is charged only for what it adds. traced_bytes(build) runs build(), returns what it made, and gives the bytes still held when it returns, measured with tracemalloc; the answer writes it. A Trie holds no word strings at all, only nodes: a dict-based TrieNode with children (a dict from one character to the child) and end (a flag), as written out in the answer. A set and a sorted list hold only references to the strings that already exist. So a fair account of the set or the list counts the strings' own bytes too: sys.getsizeof on each word, summed (the strings live whatever structure holds them). The helpers distinct_words (exactly n different random words of 3 to 10 letters), syllable_words (exactly n made-up words of two to four syllables), prefixed_words (exactly n words that each start with one of eight long stems and end in 2 to 5 more letters) and count_nodes (nodes at and below a node, iteratively) are written out in the answer.

  1. For three lists (random, syllable, prefixed) at 1,000 and at 10,000 words, build each list first and print its size. Then measure the bytes held by Trie(words), set(words) and sorted(words), and the strings' own bytes, each as bytes per word.
  2. For each row decide from the numbers: the trie's bytes against the set's bytes plus the strings', and against the sorted list's bytes plus the strings'. Print the ratio and name the smaller side with a rule written in code, not typed.
  3. Explain the trie's cost from measurements: the bytes per node (measured, and the nodes counted), against the sys.getsizeof of one node object and of its dict with 0 and with 1 key, and an estimate built from them (every leaf costs object + empty dict, every other node object + one-key dict) that must land within 10% of the measured figure.
  4. Build the closing lines from the printed numbers, so that no sentence can print when the numbers say the opposite. Libraries such as pygtrie, marisa-trie and datrie are named only: they keep their nodes in arrays rather than in Python objects.
Q35Replacing Words By Their Shortest RootEasy

A dictionary of roots (non-empty strings) and a sentence (words separated by spaces) are given. Replace every word of the sentence by the shortest root that is a prefix of it; a word with no root as a prefix stays as it is. Split the sentence with str.split() and join the answer with single spaces. A root that is empty makes no sense (it is a prefix of everything), so replace_words raises ValueError for it. The answer pastes Trie (a prefix tree of dict-based nodes with insert and a root; every node has children and an end flag), random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words of lo to hi letters, repeats allowed), and the beds BED (every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed: 3,616 lists) and PROBES (the 40 strings over "abc" of length 0 to 3).

  1. Write replace_words(roots, sentence): put the roots in a trie and, for each word, walk down it. Stop at the first end flag: that node's path is the shortest root, because every shorter prefix was passed without an end. If the path breaks first, keep the word.
  2. Write the oracle replace_scan, which sorts the roots by (length, root) and takes the first one that str.startswith accepts.
  3. Check both on the sentence in the opening example, on roots [""] (ValueError, asserted by type name), on every list in BED that holds no "" with a sentence of every non-empty probe, and on 200 seeded cases. Count what the checks covered.
  4. A student takes the first matching root in list order instead of the shortest (B35 in the code). Find the smallest roots list and word where it disagrees with the truth, with a plain search, and print both.
Q36Map Sum: Values Added Over A PrefixMedium

A MapSum stores integer values under string keys. insert(key, value) stores the value; if the key is already stored the new value replaces the old one. total(prefix) returns the sum of the values of all stored keys that start with prefix (a key equal to the prefix counts). A key may be any string, "" included, and "" is a prefix of every key, so total("") is the sum of everything. A prefix that no key starts with gives 0, and so does an empty map. Values may be negative or 0.

The answer pastes random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words of lo to hi letters over alphabet, repeats allowed) and the probes PROBES (the 40 strings over "abc" of length 0 to 3).

  1. Write SumNode (a dict children and a total) and MapSum with a dict values (key to its current value) and a trie whose every node stores the sum of the values of the keys at or below it. insert computes value - old (the old value is 0 for a new key) and adds that difference to the root and to every node on the key's path, creating nodes as it goes. total is one walk.
  2. Write the oracle DictSum, which keeps a plain dict and answers total by scanning every key with str.startswith.
  3. Check them against each other on 300 seeded scripts of 0 to 40 operations (inserts with values from -5 to 9, and totals), and on the same keys inserted in sorted and in reverse-sorted order. Count the cases hit: an empty map, "" as a key, a single key, a key that is a prefix of another, a replaced value, and a total of 0 for an absent prefix.
  4. A student adds the new value to the old one instead of replacing it (B36 in the code). Find the smallest script where it disagrees, with a plain search over short scripts, and print both answers.
Q37Search With A Wildcard LetterMedium

A word list is stored in a trie, and a pattern is made of letters and the wildcard ".", which matches exactly one letter (never zero, never two). A pattern matches a stored word when the two have the same length and every position agrees: equal letters, or a dot in the pattern. The empty pattern matches only a stored "". Stored words contain letters only. Write the search by hand, with no regular-expression module.

The answer pastes Trie (a prefix tree of dict-based nodes: insert, a root, and on every node a children dict and an end flag), syllable_words(n, rng) (exactly n different made-up words of two to four syllables), random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words, repeats allowed) and count_nodes (nodes at and below a node, iteratively), and the bed BED: every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed (3,616 lists).

  1. Write search_dots(trie, pattern, visits=None): recurse one pattern character at a time. A letter follows one child, or fails if there is none. At a dot, try every child and return True on the first full match. At the end of the pattern the answer is the node's end flag. visits, if given, is a one-item list that counts every call. The recursion is as deep as the pattern is long.
  2. Write the oracle scan_match(words, pattern), which tests every stored word character by character.
  3. Check them on every list in BED with every pattern over "a." of length 0 to 3 (15 patterns), and on 200 seeded lists of words over "abc" with patterns over "abc." of length 0 to 5. Count the cases hit: empty trie, "" stored, a single word, a word that is a prefix of another, duplicates; the lists go in given, sorted and reverse-sorted order.
  4. On 10,000 syllable words, take 100 stored words of at least 6 letters, and for 0 to 4 dots print the average number of calls for a pattern that matches (dots put in random places) and for one that cannot match (the same, with the last letter changed to "z", which no word holds). Decide from these numbers how the calls grow with the dots.
  5. A student returns after the first child at a dot (B37 in the code). Find the smallest list and pattern where it disagrees with scan_match, with a plain search, and print both answers.
Q38The Longest Word Built One Letter At A TimeEasy

A word is buildable when every one of its proper non-empty prefixes is also in the list: "apple" is buildable only if "a", "ap", "app" and "appl" are all words. A one-letter word is always buildable. longest_buildable(words) returns the longest buildable word; on a tie in length it returns the alphabetically first. The empty string is never a candidate and never needed as a prefix, so it is ignored; if there is no candidate the answer is "". Duplicates change nothing. The answer pastes Trie (a prefix tree of dict-based nodes: insert, a root, and on every node a children dict and an end flag), random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words, repeats allowed), and the bed BED: every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed (3,616 lists).

  1. Write longest_buildable(words): store the non-empty words in a trie and walk down only through nodes where a word ends, starting at the root's children that end a word. Every node reached is then a buildable word, because each prefix on the way ended one. Keep the best by (length, then alphabetical order) with a stack, not recursion.
  2. Write the oracle buildable_by_set, which puts the words in a set and tests every prefix of every word.
  3. Check them on the example below, on every list in BED, and on 200 seeded lists built so that real chains exist (random words, each followed by its prefixes with some probability), each in given, sorted and reverse-sorted order. Count what was covered: empty list, "" stored, a single word, a word that is a prefix of another, duplicates, a tie in length, and a non-empty answer.
  4. A student forgets the prefix rule and returns the longest word, ties alphabetical (B38 in the code). Find the smallest list where it disagrees, with a plain search, and print both answers.
Q39Is Any Word A Prefix Of AnotherEasy

A list of strings, such as phone numbers, is prefix-free when no entry is a prefix of another entry. Two entries that are equal count as a prefix of each other, so a list with a repeat is not prefix-free; the empty string is a prefix of every string, so "" makes any list of two or more entries fail. An empty list and a one-entry list are prefix-free. The answer pastes TrieNode (a trie node with a children dict and an end flag), random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words, repeats allowed), and the bed BED: every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed (3,616 lists).

  1. Write prefix_free(entries), which inserts the entries one at a time into a trie of TrieNodes and stops as soon as it knows: it fails when the walk passes a node where an earlier entry ended (an earlier entry is a prefix of this one, or equal to it), or when the entry ends on a node that already has children (this entry is a prefix of an earlier one). Otherwise it marks the end and goes on.
  2. Write the oracle prefix_free_sorted: sort the entries, then compare neighbours with startswith. Why neighbours suffice: if a is a prefix of c then every string s with a <= s <= c in sorted order starts with a as well, so the entry right after a does. Write also the plainest oracle, prefix_free_pairs, which tests every ordered pair, and check that the neighbour method agrees with it.
  3. Check all three on the phone-number example, on every list in BED and on 200 seeded lists over "012" (each in given, sorted and reverse-sorted order). Count what was covered: an empty list, "" stored, a single entry, an entry that is a prefix of another, a repeat, and lists that are prefix-free.
  4. A student compares neighbours in input order, without sorting (B39 in the code). Find the smallest list where it disagrees, with a plain search, and print both answers.
Q40The Shortest Unique PrefixMedium

For every distinct word of a list, find its shortest unique prefix: the shortest prefix of the word that no other word starts with. A prefix of length 0 is "", which is unique only when the list holds a single distinct word. A word that is a prefix of another word has no unique prefix, so the contract is to return the whole word for it. Duplicates in the list count once. shortest_unique_prefixes(words) returns a dict from each distinct word to its prefix, built in alphabetical order of the words.

The answer pastes CountTrie (a trie whose every node has a children dict, an end flag and a count words of the stored words at or below it; insert ignores a word already stored) with its CountNode, random_words(n, rng, alphabet, lo, hi) (exactly n seeded random words, repeats allowed), and the bed BED: every list of 0 to 3 strings over "ab" in every order, repeats and "" allowed (3,616 lists).

  1. Write shortest_unique_prefixes(words): build a CountTrie, then for each distinct word walk down it and stop at the first node whose count is 1: only this word passes through it. Check the root first (for the "" prefix). If the walk reaches the end of the word without finding one, the word is a prefix of another and the answer is the whole word.
  2. Write the oracle unique_by_scan, which for each distinct word tries prefixes by length and counts the distinct words that start with each, with str.startswith.
  3. Check them on the example, on every list in BED that has no repeats (so the lists are sets of strings), and on 200 seeded lists over "abc" that may hold repeats and "". Count what was covered: an empty list, "" stored, a single word, a word that is a prefix of another, repeats, and words whose answer is shorter than the word.
Q41Phone Keypad Words From A DictionaryMedium

DSA Topic 8's keypad words wrote every letter string a digit string could spell; filtering those against a dictionary is the brute force here: 3 or 4 branches per digit, so "7979" already has 256 strings. A trie of the dictionary lets the walk step only into letters that some word continues with, so a dead prefix is dropped at once. The answer writes Trie and syllable_words (n different made-up words of 2 to 4 syllables) out in full.

Write keypad_words(trie, digits) with this contract: digits may hold only the characters "2" to "9" (7 is pqrs, 9 is wxyz), and any other character raises ValueError before the walk starts. It returns the stored words that digits can spell, alphabetically; "" spells only the empty word, when it is stored.

  1. Build 2,000 syllable words, a trie, and a dict from each word's digit string to its words (a Python replacement for full numbers). Trace one query.
  2. Walk the trie one digit at a time, keeping the nodes still alive and the letters read so far. Count the nodes stepped into (visits, a one-item list that is None while not counting).
  3. On 200 digit strings typed from the words and 200 random digit strings, print the average number of letter strings the digits could spell (combinations) against the average number of nodes visited. Assert for each query that the words equal the dict's and that visits is at most the number of letter-string prefixes the digits could spell (the sum of the products of the first i keys' letter counts).
  4. Check against Topic 8's every-combination list, filtered by the dictionary (kept when it is a stored word), on short queries, and on every list in BED with queries of 2s (every letter of "a" and "b" is on key 2). Count the empty trie, the empty word, a word that is a prefix of another and the rejected digits, and assert each was hit.
  5. A student never checks the digits (B41 in the code). Find the first digit that raises KeyError and print it beside the contract's ValueError. Show that a dead path hides the bad digit.
Q42Suggestions After Each Typed LetterMedium

A search box shows the first 3 words that start with what has been typed so far, after every keystroke. Restarting from the root each time walks the whole prefix again: keystroke i costs i + 1 lookups. A trie lets the box keep the node it reached and take one step per letter. The answer writes Trie, ScanWords (the oracle: a set of words scanned with startswith) and syllable_words (n different made-up words) out in full.

Write suggestions(trie, typed, k=3) with this contract: it returns one list per letter of typed (so "" gives []), and list i holds the first k stored words, alphabetically, that start with typed[:i + 1] (a word equal to the prefix counts; k <= 0 gives empty lists). Once one letter has no child, no stored word starts with what is typed, so every later list is empty and no more lookups are made.

  1. Write complete_from(node, prefix, k) (the earlier completion, started at a node) and suggestions, with a lookups list that gets one item per letter, and trace one session on 2,000 syllable words.
  2. On 300 seeded sessions (a prefix of a word, about half the time with one letter replaced by a random letter, plus up to two letters after) compare every list with ScanWords.complete, and assert each keystroke made at most one lookup. Print how many keystrokes took one lookup and how many none, against the characters walked if every keystroke restarted from the root.
  3. Check the first 241 lists of BED (0 to 2 strings) with each of the 40 PROBES typed in full. Count the empty trie, the empty word, a word that is a prefix of another, duplicate words and a dead path, and assert each was hit.
  4. A student keeps the last good node when a letter fails (B42 in the code). Find the smallest list and probe where it differs, by a search over BED and PROBES, and print it beside the truth.
Q43A Trie Of Word CountsMedium

A trie that keeps a flag at each word end stores a set. To store a multiset (a word may be stored several times, and erase removes one copy) each node needs counts instead. Give every node copies (how many copies of the word ending exactly there are stored) and below (copies at the node or anywhere below it), as CountTrie did for distinct words. The answer writes count_nodes (how many nodes there are at and below a node) out in full.

Write MultiTrie with this contract:

  • insert(word) stores one more copy and returns how many copies there are now. "" is a word like any other and lives at the root.
  • erase(word) removes one copy and returns True; it returns False, changing nothing, when no copy is stored. A node left with no copy at or below it is cut off.
  • count_equal(word) is the copies of exactly word (0 if none), and count_prefix(prefix) is the copies that start with prefix (a copy equal to the prefix counts, "" counts all). Both are one walk. len is the copies stored in all.
  1. Write the class and trace six inserts and three erases.
  2. Run 300 seeded scripts of 60 operations over the 15 strings of STRS (the strings of 0 to 3 letters over "a" and "b"), checking every step against a collections.Counter (the oracle: count_prefix scans every key with startswith): the return value, len, and that the node count equals the number of distinct prefixes of the words with a count above 0. Count an insert of "", a duplicate insert, an erase of an absent word, an erase of one of several copies, an erase of the last copy and a prefix count above the exact count, and assert each was hit.
  3. A student's erase removes every copy (B43 in the code). Find, by a search over BED and STRS, the smallest list and word where it differs from the Counter, and print both.
Q44Checking A Stream Of LettersHard

Letters arrive one at a time, and after each one you must say whether the text so far ends with one of a set of words. Keeping the whole text and testing every word with endswith costs about n tests per letter and a text that grows without limit. A suffix is the start of a reversed word, so store the words backwards in a trie, keep only the last Lmax letters (Lmax is the longest word) in a collections.deque(maxlen=Lmax) as DSA Topic 11 did (a full deque drops its oldest letter silently), newest first, and walk the trie along them: each letter costs at most Lmax steps. The answer writes Trie and syllable_words (n different made-up words) out in full.

Write StreamChecker(words) with feed(ch) and this contract: feed takes one letter and returns True when the text so far ends with a stored word (a word equal to the whole text counts) and False otherwise. The empty word, if stored, ends every text, so every answer is True. Words may repeat.

  1. Write the class, and ScanChecker (the naive version and the oracle: keep the text, test each word with endswith). Feed both a stream of 3,000 letters (1,500 random syllables) against 400 syllable words. Count the trie steps (a one-item list steps that is None while not counting) and assert that no letter took more than Lmax. Print the steps per letter against the endswith tests per letter.
  2. Check the first 241 lists of BED (0 to 2 strings over "a" and "b") against every text of 0 to 5 letters over "a" and "b", letter by letter, against the scan. Count the empty list, the empty word, a word that ends another and duplicates, and assert each was hit.
  3. A student's buffer is one letter short (B44 in the code). Find, by a search over BED and the texts, the smallest failing list and text, and the smallest whose longest word has two letters or more, and print each beside the truth.
Q45Encoding Words By Shared SuffixesMedium

An encoding of a list of words is a string made of entries, each one of the words followed by "#", such that every word is a suffix of some entry. The shortest one needs an entry only for a word that is not a proper suffix of another different word: "me" is covered by "time#", so ["time", "me"] encodes as "time#" (5 characters, not 8). Duplicates count once and the empty word is a suffix of every word. The encoding lists the entries alphabetically; the empty list encodes as "" and the empty word alone as "#". The answer writes Trie and syllable_words (n different made-up words) out in full.

With a trie of the words written backwards, a word is a proper suffix of another exactly when its node has a child, so the words to keep are the leaves.

  1. Write leaves(trie, flip), encode(words) (it returns the encoding and the kept words), and the oracle encode_scan (test every pair with endswith). Trace ["time", "me", "bell", "ell", "me"].
  2. Check every list in BED (3,616 lists of 0 to 3 strings over "a" and "b"): the trie encoding equals the pair scan, every word is a suffix of some entry, and the length equals the shortest found by trying every subset of the distinct words as entries. Count the empty list, the empty word, a word that ends another and duplicates, and assert each was hit.
  3. Build 1,000 syllable words plus 500 of their endings (1,500 in all). Print the words kept, the encoding length against the words one after another, and the endswith tests of the pair scan against the characters the trie inserts, and assert the trie's count is smaller.
  4. A student builds the trie of the words as written, forward, and keeps its leaves (B45 in the code). Find the smallest list in BED where it differs, and show that its entries do not cover every word.
Q46A Trie Over Pairs Of LettersHard

Count the pairs i < j where words[i] is both a prefix and a suffix of words[j]. A word equal to the other counts, and the empty word counts with every later word. Testing every pair costs O(n^2 * L). A trie edge may be keyed by any hashable value, not only a letter, so key the edge at position t of a word by the pair (w[t], w[-1 - t]): its t-th letter from the front and from the back.

Claim: u is both a prefix and a suffix of w exactly when the pair sequence of u is a prefix of the pair sequence of w. Proof in three lines: pair t of u is (u[t], u[-1 - t]) and of w is (w[t], w[-1 - t]); u is a prefix of w when the first halves agree for every t < len(u), and a suffix of w when the second halves agree for every t < len(u); a sequence is a prefix of another only if it is not longer.

Insert the words in order into such a trie; before a word goes in, add up the number of earlier words that ended at each node of its path (the root counts the empty word). The answer writes random_words(n, rng, alphabet, lo, hi) (exactly n words of lo to hi letters, repeats allowed) out in full.

  1. Check the claim on every pair of the 121 strings over "a", "b" and "c" of 0 to 4 letters, with startswith and endswith as the oracle.
  2. Write count_by_key(words, key), count_pairs (pair keys) and the oracle count_scan. Trace a small list.
  3. Check every list in BED and 200 seeded lists of 40 words of 0 to 6 letters over "a" and "b". Count the empty list, the empty word, equal words, a prefix that is not a suffix and lists with a pair counted, and assert each was hit.
  4. On 1,200 words, print the pairs found, the pairs the scan tests and the steps the trie takes, and assert the trie takes fewer.
  5. A student keys the edges by the front letter only (B46 in the code), so it tests the prefix only. Find the smallest list in BED where it differs and print it beside the truth.
Q47Numbers In Lexicographic OrderEasy

List 1 to n in the order of their decimal strings, so "10" comes before "2". Sorting with key=str takes O(n log n * d) (d = the digits of n, since each comparison reads up to d characters) and builds n strings. Instead, notice that the numbers form an implicit trie: x has the children 10x, 10x + 1, ..., 10x + 9 (those that are at most n) and the roots are 1 to 9, with no node stored at all. A pre-order walk of it is the answer. Do it with a loop, not recursion: from cur, go down to cur * 10 when it is at most n; otherwise climb with cur // 10 while cur ends in 9 or cur + 1 > n, and then step to cur + 1. n == 0 gives [] and n < 0 raises ValueError. The answer writes Trie and words_under (the stored words of a trie in alphabetical order) out in full, for one check.

  1. Write lex_order(n) with a steps counter (a one-item list, None while not counting) and trace n = 13 and n = 100.
  2. Check against sorted(range(1, n + 1), key=str) for every n from 0 to 300, around each power of ten up to 2,000 and for 30 seeded larger n. Assert the steps are at most 2 * n + 1, and print the most steps per number.
  3. Show that a Trie of the strings "1" to "n", read with words_under, gives the same list.
  4. A student walks the same tree with roots 0 to 9 (B47 in the code). Find the smallest n where it differs and print it beside the truth.
Q48The Sum Of Prefix ScoresMedium

The score of a word is the sum, over its non-empty prefixes, of how many different words start with that prefix (the word itself counts as one of them). For ["abc", "ab", "bc", "b"] the score of "abc" is 2 + 2 + 1. Duplicates in the list count once, and the empty word has no non-empty prefix, so its score is 0. Counting each prefix by scanning all the words costs about n * N comparisons. With CountTrie (every node stores how many stored words end at or below it) one walk down a word adds up the counts of its nodes. The answer writes CountNode, CountTrie and syllable_words (n different made-up words) out in full.

  1. Write prefix_scores(words), returning (word, score) for each different word, alphabetically, and the oracle prefix_scores_scan. Trace ["abc", "ab", "bc", "b", "ab"].
  2. Check every list in BED and 200 syllable words. Count the empty list, the empty word, duplicates and a word that is a prefix of another, and assert each was hit.
  3. Check an identity: the scores add up to the sum, over every node below the root, of its count squared (each node's count is added once for each word that passes through it).
  4. A student starts the sum at the root's count, which counts the empty prefix (B48 in the code). Find the smallest list in BED where it differs and print it beside the truth.
Q49Merging Two TriesMedium

DSA Topic 13 overlaid two binary trees position by position: where both had a node the values were combined and the walk went on, and where only one had a node, that side was taken as it was. Two tries merge the same way, with a position being a path of letters. Merge trie b into trie a: a.end becomes a.end or b.end; a child that both have is merged recursively; a child only b has is adopted, meaning a points at b's own node and no copy is made, so the merge costs only the nodes the two tries share. The answer writes Trie, words_under (the stored words in alphabetical order) and count_nodes out in full.

Write merge_tries(a, b) with this contract: afterwards a stores the union of the two sets of words, its len is the number of distinct words (set again by counting the end flags: adding the two sizes would count a shared word twice), and b must not be used again, because the adopted nodes now belong to both tries.

  1. Write merge_nodes, count_ends and merge_tries. Merge ["app", "apple", "ant"] with ["apple", "apt", "bat"] and print the words and the size, beside the two sizes added.
  2. Show why b is unusable: delete a word of b that a adopted and look in a, and insert into b below an adopted node.
  3. Check every pair of lists from the first 241 of BED (0 to 2 strings; by construction 241 * 241 = 58,081 pairs): the words of a equal the union, len(a) equals its size, and the nodes equal the distinct prefixes of the union.
  4. A student replaces a shared child with b's (B49 in the code). Find the first pair in BED order where it loses a word and print it beside the union.
Q50Distinct Substrings With A Suffix TrieHard

Every substring of s is a prefix of a suffix of s. So insert every non-empty suffix of s into a trie: each node except the root is then one prefix of some suffix, which is one distinct substring, and the number of distinct non-empty substrings is nodes - 1. Building it costs n + (n - 1) + ... + 1 insert steps, which is quadratic. The answer writes Trie, count_nodes and traced_bytes (the bytes a build still holds when it returns, from tracemalloc) out in full.

  1. Write suffix_trie(s) and distinct_substrings(trie), and the oracle distinct_by_slices (a set of every slice s[i:j]). Trace "banana".
  2. Check every string over "a" and "b" of 0 to 6 letters (127 strings) against the oracle.
  3. For a random "acgt" string of 200 letters, one of 400, "ab" * 200 and "a" * 400, print the nodes, the bound n * (n + 1) / 2 + 1 (assert the nodes stay within it), the distinct substrings, and the bytes and bytes per node from traced_bytes. Print what doubling n did to the nodes of the random strings, with the verdict built from the number.
  4. A suffix tree joins every chain of one-child nodes and a suffix array stores the sorted order of the suffixes: both avoid the quadratic size, and are named here and not built. State that in a comment.
  5. A student inserts only the proper suffixes (B50 in the code). Find the smallest string where it differs and print it beside the truth.
Q51Membership: Trie Or Set, MeasuredMedium

"Is this word stored?" is the one question both a trie and a Python set answer. The trie's search walks one dict lookup per character of the word and stops at the first character with no child (a miss often stops early). The set hashes the whole string once, and CPython caches a string's hash after the first time (DSA Topic 7's hidden cost of building a key), then does one lookup in C. The bound O(L) for both hides that difference, so measure it.

Use 30,000 different made-up words (syllable_words: 2 to 4 syllables, each a consonant then a vowel) as the stored words, 10,000 of them as hit probes, and 10,000 further words that are not stored as miss probes. The helpers Trie, syllable_words (n different words from a seeded random.Random), best_of(fn) (the smallest wall time of 3 runs) and the small lists BED (every list of 0 to 3 strings over "a" and "b") are written out in the answer.

  1. Build the trie and the set from the same words and check that they answer every probe the same way, and also every string of STRS (the 15 strings of length 0 to 3 over "a" and "b") against every list in BED.
  2. Count the dict lookups of the trie on a counted copy of search (the timed code never counts): per hit and per miss. A hit must walk every character; a miss may stop early. The set makes one lookup per probe.
  3. Time [trie.search(w) for w in probes] against [w in wordset for w in probes] for the hits, the misses and both, each the smallest of 3 runs, and print the ratio trie / set for each.
  4. Print a verdict only if the ratio is at least 2 (otherwise "no verdict: within 2x"), and then a line that quotes the lookups per probe from step 2. If the verdict stands, end with one line that names what to use for membership alone (a set) and what the trie is kept for. Build every line from the variables.
Q52Prefix Queries: Trie, Sorted List Or Set Scan, MeasuredHardMust Do

A prefix query asks about the stored words that start with a given prefix (a word equal to the prefix counts, and "" is a prefix of every word). Words are strings of the letters a to z. Two questions are measured here, each answered three ways:

  • Count the words with the prefix. A counting trie keeps, in every node, an int words: the number of stored words that end at that node or below it, so count_prefix is one walk of one dict lookup per character. The sorted list gets the count from two bisect_left calls (DSA Topic 3's autocomplete): the position of the prefix, and the position of the first string past every word that starts with it, prefix[:-1] + chr(ord(prefix[-1]) + 1) (this works because the letters are a to z; "" counts every word). The set scan tests every word with str.startswith.
  • Complete: the first 10 stored words with the prefix, alphabetically. The trie uses complete(trie, prefix, k), an iterative walk with an explicit stack that stops as soon as it has k words (k <= 0 gives []). The sorted list slices from the first position, up to 10 words and never past the upper bound.

These helpers are written out in the answer: CountTrie (a plain trie: insert returns False for a word already stored, search is exact membership; with insert, search, count_prefix and _walk, which returns the node a string leads to, or None), complete, ScanWords (the brute-force oracle: the words in a Python set, every question answered by scanning them with str.startswith), syllable_words (n different made-up words from a seeded random.Random) and best_of(fn) (the smallest wall time of 3 runs). The small lists BED (every list of 0 to 3 strings over "a" and "b", repeats and "" included) and PROBES (the 40 strings of length 0 to 3 over "a", "b" and "c") are written out too.

  1. Write bisect_count and bisect_complete, and check the trie, the set scan and the sorted list agree on count_prefix and on the first 2 completions for every list in BED with every probe in PROBES.
  2. Take 30,000 syllable words and 1,000 prefixes of 1 to 4 letters, each cut from a random stored word. Count the work on counted copies (the timed code never counts): the dict lookups of the trie's walk against the string comparisons of a hand-written bisect_left (check each copy returns the same count as the plain code). Print the average per query.
  3. Time the plain code, each the smallest of 3 runs, per query: counting with the trie, with bisect_count and with the set scan (the scan on the first 20 prefixes only, divided by 20, because it reads every word), and the first 10 completions with complete and with bisect_complete. Check that both give the same words.
  4. Print a verdict only where it is earned: the scan against the trie when the ratio is at least 2; for the trie against bisect on counting print the ratio alone (a small gap, it moves from run to run) and let the lookups against comparisons from step 2 decide (print one line naming which method did fewer steps per query); for the completions, a verdict when the ratio is at least 2. Name sortedcontainers (not imported) as a sorted list that stays sorted as words arrive. Build every line from the variables.
Q53Building The Index, MeasuredMedium

A trie has to be built before it answers anything, and a set or a sorted list from the same words is built by one library call. Measure what the build costs, and how many prefix queries it takes to pay for it.

The helpers Trie, CountTrie (a trie whose nodes count the words at or below them, so count_prefix is one walk), ScanWords (the oracle: the words in a Python set, every prefix question answered by scanning them with str.startswith), syllable_words (n different made-up words from a seeded random.Random) and best_of(fn) (the smallest wall time of 3 runs) are written out in the answer. Time plain code only.

  1. For 10,000 and then 30,000 syllable words, time Trie(words), set(words) and sorted(words), each the smallest of 3 runs. Print the total characters, the three times, the nanoseconds per character of the trie build, and the ratios trie / set and trie / sorted.
  2. Print a build verdict for each size and each comparison only when the ratio is at least 2, otherwise "no verdict: within 2x", from the same printed numbers.
  3. Time one counting query per prefix two ways at 30,000 words: CountTrie.count_prefix on 1,000 prefixes of 1 to 4 letters, and the set scan on the first 20 of them (divide by 20). Compute the break-even against the scan: the smallest number of queries q for which build + q * trie query is under q * scan query (build the trie the queries run on, a CountTrie, and find q by a loop; never subtract two timed runs). Time each piece on its own and combine them by arithmetic; never subtract two timed runs of the same code. Print the totals for q = 1, the break-even minus 1, the break-even and 1,000, with the cheaper one named from the totals.
  4. Say why no break-even is claimed against the sorted list: the counting queries differ from it by a small ratio that moves from run to run, and the sorted list wins the completions (measured earlier in this topic).
Q54Top-k Kept In Every NodeHard

An autocomplete box shows the best few words for a prefix, ranked by a weight. Collecting every word below the prefix and ranking them costs as much as the subtree is big. Instead keep, in every node, the 5 best (-weight, word) pairs among the stored words at or below it, best first (the biggest weight first, ties by the word alphabetically; the minus sign makes the pairs sort that way). Then the best 5 words for a prefix are read off one node, one walk of one dict lookup per character.

Write TopKTrie with insert(word, weight) and top(prefix):

  • every word has an int weight; insert may raise a weight but never lowers it. A word already stored with a weight at least as big changes nothing and returns False; otherwise it returns True;
  • on a new or raised word, every node on its path (the root included, "" is a word like any other) removes the word's old pair, if its list holds one, adds the new pair in order and keeps only 5;
  • top(prefix) returns up to 5 (word, weight) pairs, best first, [] for a prefix the walk cannot follow and for an empty trie.

The helpers Trie (the plain trie, with insert, search, starts_with, delete and _walk), words_under(node, path, out) (appends every word at or below a node, alphabetically), count_nodes(node), syllable_words (n different made-up words from a seeded random.Random) and traced_bytes(build) (the bytes build() leaves allocated, with tracemalloc) are written out in the answer.

  1. Trace it on 8 small weighted words, and raise one weight.
  2. Check it on 300 seeded scripts of inserts and queries over the words of up to 4 letters over "a" and "b" ("" included, repeated inserts, lower weights, equal weights, prefix pairs) against two oracles: collecting every word with words_under and ranking them, and a plain sorted of the stored words that start with the prefix. Count the cases each script reached, assert each count is above 0, and count any exception as a failure.
  3. On 10,000 syllable words with weights 1 to 1,000, measure the memory of the plain trie against the same trie with a list in every node (traced_bytes, words and weights built first), and check that both have the same number of nodes.
  4. For 300 prefixes of 1 to 3 letters, count the dict lookups of top against the nodes a collect-and-rank query visits (the walk plus every node of the subtree), checking the answers are equal.
  5. A student updates a weight by adding the new pair and never removing the old one (StaleTopKTrie). Find, by a scan in increasing size over inserts of "", "a" and "b" with weights 1 to 3, the smallest script where top differs from the truth, and print both.
Q55Word Search At Scale: Cutting Found WordsHardMust Do

A board is a list of rows, each a list of one-character strings. A word is on the board when some path spells it: the path starts at any cell, each next cell is directly up, down, left or right of the one before (no diagonals), and no cell is used twice. The empty word is never on a board. A trie stores the dictionary as paths from a root: each node has a dict children (one character to the child below it) and a flag end, True when a stored word ends there. A call is one call of a search's recursive helper, which enters one cell. A board search marks a cell used when it enters it and unmarks it when it leaves (DSA Topic 8's permutation generator marks and unmarks a choice the same way), so the marks always describe the current path. The trie prunes: a path stops as soon as no stored word starts with its letters.

Two searches count calls: find_words(board, trie, calls) walks the trie along every path, and board_has(board, word, calls) searches for one word alone, adding one to calls[0] per call. Their baseline is every_path_calls(board, max_len): the calls of a walk with no trie that extends every path from every cell up to max_len cells. every_path is the same walk with no counter, returning the number of paths, and is the one that gets timed. The new part is cutting found words: once a word has been reported it need not be found again, so remove it from the trie as it is found. find_words_cutting clears the end flag of a found node, and after a node's subtree has been searched it removes a node that has no children and ends no word from its parent. Later paths then stop at the cut, and the trie ends holding only the words that were not found.

These helpers are written out in the answer: Trie, syllable_words (n different made-up words of 2 to 4 syllables, each a consonant then a vowel, from a seeded random.Random), syllable_board and random_board (seeded boards), board_words(board, max_len) (an oracle that spells every path with itertools.permutations), count_nodes, and best_of(fn) (the smallest wall time of 3 runs). The small lists BED (every list of 0 to 3 strings over "a" and "b", repeats and "" included) are written out too.

  1. Write find_words_cutting and check it on 30 seeded 3 x 3 boards over "abc" (60 sampled words of 1 to 5 letters, plus "" and a repeated word) and 20 syllable boards, against find_words, board_words and one board_has per word.
  2. Print the calls of find_words, of one board_has per word, and of every_path_calls, for 10,000 syllable words on a 5 x 5 and a 6 x 6 syllable board and for 1,000 words on the 6 x 6 board, with the words found and both ratios against the trie. Say from the two 6 x 6 rows what happened to the saving as the dictionary grew ten times.
  3. Time the plain code (counters off), each the smallest of 3 runs: the trie against one search per word on the 5 x 5 board, and against every_path on the 6 x 6 board. Print a verdict only when the ratio is at least 2.
  4. Run find_words_cutting on a fresh trie of the 10,000 words for each board and print the calls before (plain find_words) and after cutting, a second pass on the already cut trie, the nodes before and after, and what share of the calls was saved. Assert that exactly the found words were removed.
  5. A student cuts a found node at once, children and all, so longer words below it are never reached (cut_found_with_children=True). Find by a scan (boards of fewer cells first, stored lists in BED order) the smallest failing board and word list, and print the result beside the truth.
Q56Spell-Check: Generate Or Walk, MeasuredHardMust Do

A spell checker looks for the stored words exactly one edit from a misspelling. One edit is: delete one character, insert one, replace one by a different one, or swap two adjacent different characters (DSA Topic 7's spell checker made the same four edits). A word is never one edit from itself. There are two ways to find them:

  • Generate: edits1(word, alphabet) builds the set of every string one edit away (with 26 letters, distinctly 52L + 25 of them for a word of L letters with no two equal neighbours), and near_by_edits keeps the ones in the set of stored words.
  • Walk: near_by_trie(trie, word, visits) follows the word down the trie and, at each position, spends its single edit in every way the trie allows (delete the letter, insert any child's letter, replace the letter by a different child's letter, swap it with the next one), then follows the rest of the word exactly. visits, if given, is a one-item list that counts every step from a node to a child.

These helpers are written out in the answer: Trie (a dict-of-children trie with end flags), one_edit(a, b) (a direct test of the definition), edits1, near_by_edits, near_by_trie, near_brute(word, words) (the oracle: one_edit against every word of the list), syllable_words (n different made-up words from a seeded random.Random) and best_of(fn) (the smallest wall time of 3 runs). corrupt(word, rng) applies one random edit.

  1. For 1,000 and for 10,000 syllable words, make 300 corrupted words (one random edit of a random stored word each). For every one, check that the walk returns the same set as the generator, that every word it returns passes one_edit, and (on 20 of them) that near_brute agrees. Print the average steps of the walk, the average distinct candidates, their ratio, the average hits, and the times of both searches over the 300 queries, each the smallest of 3 runs on plain code (counters off).
  2. Print the counts first and decide from them. Print the time ratio generate / walk with no direction word ("ratio only"), because it moves with the load, and one line per dictionary size that names, from the counts, which method did fewer steps.
  3. Make queries that have no stored word one edit away: for L = 2, 4, 6, 8, 10 and 12, 50 random strings with no two equal neighbours (found by filtering). Print the average steps of the walk against the distinct candidates and 52L + 25, and assert the candidates equal the formula. Say from the table how the steps and the candidates changed from L = 2 to L = 12.
  4. Time near_brute once on 20 corrupted words at 10,000 words, for scale, and print the ratio against the walk. End with a line built from the counts of step 1.
Q57Rank And Select By Prefix CountsMedium

DSA Topic 14's order statistics keep a size in every tree node: select(i) finds the i-th smallest by comparing i with the left subtree's size, and rank counts the keys below one. A trie with a count in every node (a CountTrie: each node's words is the number of stored words that end at it or below it, "" is a word like any other and a word stored twice counts once) can do the same for strings in alphabetical order, where a word comes before the longer words that begin with it.

  • rank(trie, w) is the number of stored words strictly before w alphabetically, whether w is stored or not (so it equals bisect_left on the sorted list of the stored words). Walk down w: at each node add 1 if a word ends there (it is a proper prefix of w), and add the words of every child whose letter is smaller than w's next letter. Stop when the walk cannot follow w.
  • select(trie, i) is the i-th stored word alphabetically, counting from 1. At each node, a word ending there comes first, then the children in sorted order; skip a child's whole subtree when i is more than its words. i outside 1..len(trie) raises IndexError.

The helpers CountNode, CountTrie (with insert, search, count_prefix, delete and len), syllable_words (n different made-up words from a seeded random.Random) and the small lists BED (every list of 0 to 3 strings over "a" and "b", repeats and "" included) with PROBES (the 40 strings of length 0 to 3 over "a", "b" and "c") are written out in the answer.

  1. Write rank and select (with an optional counter of the child keys looked at) and trace them on ["bat", "bath", "be", "a", "an", "and", "car"].
  2. Check every list in BED with every probe: rank against bisect_left on sorted(set(words)); every select(1..n) against the sorted list; select of 0, -1 and n + 1 raises IndexError (assert the type name); and select(rank(w) + 1) == w for each stored word. Count how many lists were empty, held "", held repeats and held a word that is a prefix of another, and assert each is above 0.
  3. On 10,000 syllable words check 2,000 probes (half stored, half not) and 2,000 positions against the sorted list, and print the child keys looked at per call against the cap A * (L + 1), with A and L measured from the trie.
  4. A student's rank also counts w itself when it is stored (count_self=True). Find by a scan of BED and PROBES in order the smallest list and probe where it differs from bisect_left, and print it beside the truth.
Q58Radix Tree Memory And Lookups, MeasuredMedium

A radix tree (a compressed trie) turns every chain of trie nodes that have one child and end no word into one edge labelled with the chain's letters, so it has fewer nodes. compress(node) builds one from a finished trie (the trie is unchanged); each RadixNode has a label (the letters on the edge into it), children keyed by the first letter of each child's label, and an end flag. radix_search(root, word) compares a word against one label at a time, and radix_starts_with(root, prefix) allows a prefix to end partway along an edge. How much memory does that save, and does it make lookups faster? Measure both. (Memory per word against a set and a sorted list was measured earlier in this topic; here only a radix tree is added to the comparison, and the set appears in one column.)

The helpers Trie, count_nodes, RadixNode, compress, radix_search, radix_starts_with, the seeded builders distinct_words, syllable_words and prefixed_words (each exactly n different words), traced_bytes(build) (the bytes build() leaves allocated, with tracemalloc) and best_of(fn) (the smallest wall time of 3 runs) are written out in the answer, with the small lists BED and PROBES. count_radix_nodes counts a radix tree's nodes.

  1. Check that radix_search and radix_starts_with agree with the trie on every list in BED (every list of 0 to 3 strings over "a" and "b", repeats and "" included) with every probe in PROBES (the 40 strings of length 0 to 3 over "a", "b" and "c").
  2. Make three lists of 10,000 different words: random letters (3 to 10 letters), syllables (2 to 4 syllables, a consonant then a vowel each) and words that start with one of 8 long stems plus 1 to 5 letters. For each, measure with traced_bytes (words built first, so only the structure counts) the trie, the radix tree built from it, and a set plus the words' own strings (sys.getsizeof each). Print nodes, bytes per word and the radix/trie ratio. Note that labels of 2 or more letters are new strings built by compress, so they are in the radix tree's bytes.
  3. On each list check 10,000 probes (half stored, half with the last letter changed): radix_search equals Trie.search on all of them, then time both, each the smallest of 3 runs. Print the ratios (trie time / radix time) as ratios only, with no verdict either way, because they move between runs.
  4. End with lines built from the table: whether the radix tree was smaller than the trie on every list, which list saved the most, and on how many lists it still used more bytes per word than a set plus its strings.
Q59A Trie Over Bits: Maximum XORHardMust Do

Given a list nums of non-negative ints, find the largest a ^ b (bitwise xor) over two numbers at different positions i < j of the list; equal values at two positions are a pair, and their xor is 0. A list of fewer than 2 numbers, or one holding a negative number, raises ValueError. Checking every pair costs O(n^2) xors.

A trie over bits does it in O(n * B): let B be the largest number's bit_length() (0 for a list of zeros), store every number as a path of B bits, high bit first, in a binary trie where a node has two children (kids[0] and kids[1], or None). To find the best partner of x, walk down from the root and, at each bit, prefer the child with the opposite bit of x (a 1 in a higher bit is worth more than every lower bit together), and take the same bit only when the opposite child is missing. The number y spelled by the walk gives x ^ y; the answer is the largest over every x. (x itself is in the trie, so a walk can end at y = x with xor 0, which never beats a real pair when there are 2 or more numbers.)

These helpers are written out in the answer: BitNode (a node with a two-slot list kids), max_xor(nums, steps) (the trie method; steps, if given, is a one-item list that counts every move to a child), max_xor_pairs(nums, xors) (the oracle: itertools.combinations over every pair of positions; xors, if given, counts the xors) and best_of(fn) (the smallest wall time of 3 runs).

  1. Write the helpers, trace [3, 10, 5, 25, 2, 8], and check that fewer than 2 numbers and a negative number raise ValueError (assert the type name) and that [5, 5] and [0, 0, 0] give 0.
  2. Check 2,000 seeded lists of 2 to 8 numbers, each below 2^k for a random k from 0 to 6, in random, ascending and descending order, against max_xor_pairs. Count the cases reached (all equal, with a zero, with duplicates, ascending, descending, largest number 1, all zeros), assert each is above 0, and count any exception as a failure.
  3. For 1,500 random numbers below 2^30 count the xors of the pair loop against the steps of the bit trie on counted copies. Both counts are fixed by how the input is built (n(n - 1) / 2 and 2 * n * B): assert them and say so. Then time both plain, each the smallest of 3 runs, and print the ratio with no direction word ("ratio only"), because it moves with the load. Print what doubling n does to each count.
  4. A student prefers the same bit instead of the opposite one (prefer_same=True). Find by a scan of every list of 2 and then 3 numbers below 4 the smallest failing list and print it beside the truth.
Q60Prefix And Suffix SearchHard

Given a list of words, answer f(prefix, suffix): the largest index of a word that starts with prefix and ends with suffix, or -1 if there is none. The empty prefix and the empty suffix match every word, a word listed twice has its larger index win, and "" is a word like any other. A scan tests every word on every query.

One trie answers it in the time it takes to read the query. For every word and every suffix of it (the empty suffix and the whole word included) insert the key suffix + "#" + word, and let every node on the key's path (the root too) remember the largest index that passed through it. A query walks suffix + "#" + prefix: the suffix comes first because the # then separates it from a word that starts with the prefix, and the walk's last node holds the answer. The marker # must be in no word: a word that holds one raises ValueError, and so does a query that holds one.

The helpers random_words (exactly n random words of lo to hi letters from a seeded random.Random), Trie, count_nodes, traced_bytes(build) (the bytes build() leaves allocated, with tracemalloc) and the small lists BED (every list of 0 to 3 strings over "a" and "b", repeats and "" included) are written out in the answer. scan_f is the oracle.

  1. Write PrefixSuffixIndex (with f(prefix, suffix, lookups), where lookups is an optional one-item counter) and trace it on ["apple", "ample", "maple", "apply", "apple"]; check that a word with # and a query with # raise ValueError (assert the type name).
  2. Check every list in BED with 64 pairs of short probes, and 300 seeded lists of up to 12 words of 0 to 6 letters over "a" and "b", against scan_f. Count the cases among the BED lists (empty list, "", a single word, a word that is a prefix of another, repeats, ascending and descending order), and assert each is above 0.
  3. On 1,000 random words of 3 to 10 letters count the keys, the characters inserted (by the formula and as counted), the nodes and the bytes, against a plain trie of the same words. The suffix parts alone are the sum of L(L + 1) / 2 per word, about L^2 / 2.
  4. On 500 queries count the dict lookups of f (at most len(prefix) + len(suffix) + 1 each) against the words the scan tests.
  5. A student keeps the first index that reaches a node instead of the largest. Find by a scan of BED in order the smallest list and pair where it differs, and print it beside the truth.
Q61Finding Dictionary Words In A TextMedium

A text with no spaces ("kabodunimo...") may hold stored words anywhere inside it, overlapping each other. An occurrence is a pair (start, word): the stored word word appears in the text beginning at index start. The empty word is never reported, and the answer lists occurrences by start, and for one start by word (which is by length, because the words found at one start are prefixes of each other).

From each start, walk the trie along the text: every node passed on the way with an end flag is one occurrence, so one walk can report several words ("a" and "aa" in the text "aa") and stops at the first letter with no child. The common alternative is str.find once per stored word, looping to find every overlapping hit. A third method, the Aho-Corasick automaton, reads the text once and never restarts at each start; it is named here and not built.

  1. Write find_all(trie, text), and the oracle find_all_scan(words, text) (try text.startswith(w, i) for every word at every position). Check them on every list of BED against every text in STRS (the 15 strings of 0 to 3 letters over "a" and "b") and on 300 seeded lists with texts of 0 to 12 letters. Count the empty trie, a stored "", a single word, a word that is a proper prefix of another, duplicates, sorted and reverse-sorted lists, a text with no occurrence and a text with several, and assert each was hit.
  2. Build 2,000 different syllable words and a text of exactly 12,000 letters made of stored words and single syllables, and check find_all against find_all_by_find (one str.find loop per word) on the whole text, and against the startswith oracle on its first 800 letters.
  3. Count the trie's steps (moves from a node to a child, on a counted copy) against the start positions str.find has to consider (len(text) - len(w) + 1 for each word), then time find_all and find_all_by_find, each the smallest of 3 runs, and print the ratio.
  4. A student stops each walk at the first word it finds (B61 in the code). Search for the smallest list and text where that differs from the truth and print both.
Q62Autocomplete That Tolerates One TypoHard

Autocomplete lists the stored words that start with what the user typed. A typo makes it list nothing. So list the words that start with the typed text p or with any string one edit from p, where one edit is as in DSA Topic 7's spell checker: delete one character, insert one, replace one by a different one, or swap two neighbouring different characters. The answer is the sorted list of such words, each once (a word may start with several candidates). The oracle generates every candidate with edits1(p, alphabet) (written out in the answer; the alphabet holds every letter the stored words use) and tests each stored word with str.startswith.

The trie does the same without generating candidates: walk p down the trie and at each position spend the single edit in every possible way, following the rest of p exactly. Every node it ends on is the end of a candidate that starts some stored words, so the answer is the words below those nodes.

  1. Write near_prefix_nodes(trie, p, visits=None) (the nodes reached by p itself and by each string one edit from p, keyed by that string; visits, if given, is a one-item list counting every move from a node to a child) and complete_typo(trie, p, visits=None) built on it with words_under. Trace "cet" on WORDS.
  2. Check against the oracle on the 241 lists of at most 2 strings of BED with each of the 40 PROBES, with the alphabet "abc". Count the empty trie, a stored "", a single word, a proper-prefix pair, duplicates, sorted and reverse-sorted pairs, and the queries where the answer needs an edit and where it needs none, and assert each was hit.
  3. On 1,000 syllable words and 60 typed texts (3 to 5 letters from a stored word, each with one random edit), check the walk against the oracle and print the trie's steps per query next to the distinct candidates the oracle generates.
  4. A student leaves the typed text itself out of the candidates (B62 in the code). Search for the smallest list and probe where it differs and print both.
Q63Word Counts: Trie Or Counter, MeasuredMedium

The counting trie from earlier in this topic (MultiTrie: every node keeps copies, the copies of the word ending there, and below) counts words as they stream in, with one walk of L lookups per word. Python already has a tool for the same job, collections.Counter, which does one hash lookup per word in C (DSA Topic 7). Which should count the words of a text?

Use 100,000 tokens drawn from 2,000 different syllable words (syllable_words), with the earlier words drawn more often (weight 1 / (rank + 1)), so the counts differ. The class MultiTrie, its node MultiNode and the helpers syllable_words and best_of (the smallest wall time of 3 runs) are written out in the answer.

  1. Count the tokens both ways and check that the counts agree on every word. Also fuzz 300 seeded token lists over the 15 strings of STRS (0 to 3 letters over "a" and "b", "" included) against a Counter, counting the empty list, a list with "", a single token, a token that is a proper prefix of another and a repeated token, and assert each was hit.
  2. Count the dict lookups each method makes (the trie's are one per character, a count the answer asserts rather than measures) and time the two ways, each the smallest of 3 runs, printing the ratio.
  3. List the 10 most common words, ties broken by the word (alphabetical order). Counter.most_common breaks ties by first appearance: show a small list where the two rules differ, and give the trie's top 10 with the explicit rule.
  4. Count the tokens that start with one prefix both ways: one walk of the trie, against a scan of the 2,000 keys of the Counter with startswith.
Q64One Dict For The Whole TrieMedium

A trie node costs an object and a dict of its own; the answer measures what that comes to per node. A trie needs less than that: it is a set of edges, each saying "from node u, the character c leads to node v". Keep every edge of the whole trie in one dict: the key is the pair (u, c) and the value is the child's id v; the root is id 0 and each new node takes the next unused id. A second structure, a set of ids, holds the nodes where a word ends. There are no node objects at all.

Write FlatTrie with insert(word) (returns whether the word was new), search, starts_with and len. There is no delete, so nothing is cut off and every node other than the root leads to a stored word. starts_with("") is True exactly when a word is stored. The class Trie (with TrieNode), syllable_words, traced_bytes (bytes still held when a build returns) and count_nodes are written out in the answer.

  1. Write the class and trace three inserts, printing the edge dict and the end set.
  2. Check that FlatTrie equals Trie (the same search and starts_with for each of the 40 PROBES, and the same len) on every list of BED.
  3. Build both from 10,000 different syllable words, with the words made first so that only the structure is counted, and print the bytes per word and per node for each, and the ratio.
  4. A student forgets to advance the next unused id (B64 in the code). Search for the smallest list and probe where it differs from Trie and print both.
Q65The k-th Number In Lexicographic OrderHard

Write the numbers 1 to n in the order of their decimal strings (1, 10, 11, ..., 19, 2, 20, ..., because "10" < "2"). Which one is the k-th, with k counting from 1? The oracle sorts: sorted(range(1, n + 1), key=str)[k - 1]. That builds n strings and takes O(n log n); for n = 10^9 it is out of reach.

The numbers form an implicit 10-ary trie: x has the children 10x, 10x + 1, ..., 10x + 9 (those at most n), and nothing is stored. A trie that keeps a count at each node can skip a whole subtree when k is larger than its count; here the count can be computed instead of stored. The numbers that start with the digits of p, with p itself counted, are the numbers in [p, p + 1), then in [10p, 10p + 10), then in [100p, 100p + 100), and so on, each range cut at n + 1. That is one step per digit.

  1. Write count_under(p, n, steps=None) (how many of 1..n start with the digits of p; steps, if given, is a one-item list that counts every range looked at) and kth_lex(n, k, steps=None). Start at cur = 1 with k - 1 numbers still to pass. While any remain: let c = count_under(cur, n). If the numbers still to pass are at least c, skip the whole subtree (cur += 1, subtract c); otherwise step down to the first child (cur *= 10, subtract 1). Raise ValueError unless 1 <= k <= n.
  2. Check against the sorting oracle for every k of every n from 1 to 300, and for n in 500, 999, 1000, 1001, 1999 and 2000, then for 30 seeded n up to 2,000 with 20 seeded k each. Assert the ValueErrors by type name.
  3. For n = 10^9 count the steps over 2,000 seeded k and for the last k = n, assert the bound 10 * d * d for d digits, and print the steps next to the k - 1 numbers that listing them one by one would pass.
  4. A student cuts each range at n instead of n + 1 (B65 in the code). Search for the smallest n and k where it differs and print both.
Q66Sorting Strings: Trie Walk Or sorted(), MeasuredMedium

Walking a trie in alphabetical order lists its words sorted: no word is ever compared with another, each character is looked at once while the trie is built, and a node's children are ordered by one tiny sort of their keys. That is a radix sort that looks at the most significant letter first (DSA Topic 9 built LSD radix sort; this is the most-significant-digit-first version, named here; Topic 9 also showed that comparing two strings costs up to their common prefix): it splits the words by first letter, then by second, and never compares two whole strings. sorted() is Timsort in C, comparing whole strings. Which is faster for sorting 30,000 words?

The helpers Trie (with TrieNode), words_under (the stored words below a node in alphabetical order), count_nodes, syllable_words, distinct_words (n different random words) and best_of (the smallest wall time of 3 runs) are written out in the answer. Use two lists of exactly 30,000 different words: syllable words (2 to 4 syllables) and random words of 3 to 10 letters from "a" to "z".

  1. Write trie_sort(words) (build a Trie, then list it with words_under) and check that its output equals sorted(words) on both lists. Also check it on every list of BED with the repeats removed.
  2. Count, for each list: the characters N and the trie's nodes m, and the string comparisons sorted() makes (on a counted copy: a str subclass whose __lt__ counts).
  3. Time build plus walk against sorted(), and the walk alone (on an already built trie) against sorted(), each the smallest of 3 runs, and print the ratios.
  4. Print a verdict for build plus walk only if its ratio is at least 2. The walk alone prints its ratio with no verdict either way.
Q67A Changing Dictionary: Trie Or Sorted ListHard

A dictionary that keeps changing (words added, words removed, "how many words start with ...?" asked in between) can be a CountTrie (every node counts the words at or below it, as earlier in this topic) or a sorted list kept in order with bisect. The list adds a word with insort (an insert) and removes one with del, and each of those shifts every element after the position, O(n) per update; a prefix count is two bisect_left calls, O(log n) comparisons. The trie does an update in O(L) dict lookups however many words it holds, and a count in O(L). So there should be a size where the shifts cost more than the walks. Find it by measuring; nobody has measured it for this machine.

A script is a list of steps ("add", w), ("del", w) and ("count", p). add stores w if it is absent and returns whether it was new, del removes w if it is stored and returns whether it was, and count returns how many stored words start with p ("" counts all). The list answers count with bisect_left(lst, p[:-1] + chr(ord(p[-1]) + 1)) - bisect_left(lst, p) (DSA Topic 3's upper bound) and len(lst) for p == "". A script is valid when each add is of a word not stored at that moment and each del of a stored one. The class CountTrie (with CountNode), ScanWords (a set that answers every question by scanning all the words with startswith: the oracle), syllable_words (n different made-up words of 2 to 4 syllables from a seeded generator) and best_of (the smallest wall time of 3 runs) are written out in the answer.

  1. Write the list's three operations and the trie's, and fuzz 300 seeded scripts of 40 steps over the 15 strings of STRS (0 to 3 letters over "a" and "b", "" included, absent deletes and duplicate adds included), plus one script that adds STRS in sorted order and one in reverse order and then removes them all: the trie, the list and ScanWords must return the same value at every step, and the list must stay equal to sorted() of the oracle's words. Count the "" word, a duplicate add, a delete of an absent word, a count of "" and a count above 1, and assert each was hit.
  2. For 10, 30, 100, 300, 1,000, 10,000, 30,000 and 100,000 stored words make a valid script of 1,500 steps, a third each, and count on counted copies: the elements the list shifts per update, the dict lookups the trie makes per update (a walk to check, then a walk to count), and the bisect_left calls per count.
  3. For the four largest sizes time the whole script on each structure, then the updates alone and the counts alone, each the smallest of 3 runs (the state is put back after each run, and that is not timed), and print list / trie for each. Print no verdict from the clock: only the ratios.
  4. Print the first size where the shifted elements per update exceeded the trie's lookups per update, say what the counts cannot tell (one shifted element is a pointer copied by C, one lookup is a Python-level dict step), and print how the whole-script ratio moved from the smallest to the largest of the timed sizes.
Q68The Deepest Shared PrefixMedium

The deepest shared prefix of a set of words is the longest string that is a prefix of at least two different stored words, where a word counts as a prefix of itself ("a" and "aa" share "a"). When several shared prefixes have the same longest length, the answer is the alphabetically smallest of them. The empty string is a prefix of every word, so any two words share at least "". With fewer than two different words stored there is no answer: return None.

In a CountTrie (every node counts the words at or below it, as earlier in this topic) a prefix is shared by at least two words exactly when its node has a count of at least 2. So the answer is the deepest node with a count of at least 2, and the walk only needs to enter children whose count is at least 2. The oracle rests on this idea: for sorted words u <= v <= w, any prefix shared by u and w is also a prefix of v, so the longest shared prefix over all pairs is found between two neighbours in sorted() order. The answer also checks that idea against every pair of words on the small lists.

  1. Write deepest_shared(trie) and the oracle deepest_shared_sorted(words). Check them on every list of BED, and check the neighbour idea against every pair of words (itertools.combinations) on each of them.
  2. Fuzz 300 seeded lists of 2 to 30 words (1 to 5 letters over "a" and "b"), and count the lists with fewer than two different words, an answer of "", an answer that is itself a stored word, and a tie between two shared prefixes of the same length, and assert each was hit.
  3. Run it on 10,000 different syllable words and on 2,000 words that begin with one of 8 long stems (prefixed_words); print each answer, how many words share it, and how many nodes the walk entered against all the nodes of the trie.
  4. A student looks for the deepest node with two or more children (B68 in the code). Search for the smallest list where it differs from the truth and print both.
Q69Tokenising By The Longest MatchHard

A text with no spaces ("thecatsat") can be cut into stored words by a rule. This question uses one rule and states it: at each position take the longest stored word that starts there, then continue after it. If no non-empty stored word starts at some position the result is None. The empty text gives [], and the empty word is never taken (it would make no progress). The trie finds the longest word at a position by walking the text down the trie and remembering the last node passed that ends a word.

This is a rule, not a claim that it is the best way to cut a text: it can fail where another cut exists. Whether any cut into stored words exists at all is the word break problem, taught in DSA Topic 21 and not solved here.

  1. Write tokenise_longest(trie, text), and the oracle tokenise_scan(words, text) that applies the same rule by trying every stored word at each position with text.startswith(w, i) and keeping the longest. Check them on every list of BED with every text of STRS (the 15 strings of 0 to 3 letters over "a" and "b"), and count the empty text, a result of None, a result with several words, a stored "", a list with a proper-prefix pair, and a text where the longest rule and the shortest rule give different cuts, and assert each was hit.
  2. Show the rule failing where another cut exists: the words "ab", "abc", "cd" and the text "abcd".
  3. On 2,000 syllable words, build 500 texts by joining 8 random stored words with no spaces. Count how often the rule returns the words that were joined, how often it returns a different cut of the same text, and how often None (print the words of the first such text: they are a valid cut), and count the trie's steps per letter of text.
  4. A student takes the shortest match instead (B69 in the code). Search for the smallest list and text where it differs from the longest rule and print both.
Q70Trie, Set Or Sorted List: Choosing, MeasuredHardMust Do

A programmer must store a fixed dictionary of words and answer questions about it. Three structures can hold it, and each is better at some questions. Measure every cell of one table instead of guessing. The dictionary does not change in this question: no word is added or removed after it is built.

The three structures and what each one answers (all words are lowercase strings; alphabetical means Python's string order, as sorted() gives; "" counts as a word and as a prefix of every word):

  • CountTrie (Trie: the same tree without counts): a prefix tree whose nodes each hold a dict of children, an end flag and words, the number of stored words at or below the node. search(w) is True only for a stored word. count_prefix(p) is how many stored words start with p (a word equal to p counts, "" counts all) and takes one walk of len(p) dict lookups. complete(trie, p, k) returns the first k stored words that start with p, alphabetically, and [] when k <= 0 or nothing starts with p.
  • A set (wrapped in ScanWords, a Python set whose prefix questions scan every stored word with str.startswith): membership is w in set, one hash and one lookup. The prefix count scans all the words; the first k completions scan all the words, sort the matches and keep k; all the words in order is sorted(set).
  • A sorted list made once with sorted(words): membership is one bisect_left and one equality test; the prefix count is bisect_left(lst, upper) - bisect_left(lst, p) with upper = p[:-1] + chr(ord(p[-1]) + 1), the string just above every word that starts with p (and len(lst) for p == ""); the first k completions are bisect_left to the first word that is at least p and then reading words while they start with p, up to k; all the words in order is a copy of the list.

The six cells (rows of the table) are: membership (hits and misses), the prefix count, the first 10 completions, all the words in order, building from the unsorted words, and the bytes per word of the structure alone (the strings are made first, so only the structure is counted). The helpers CountNode and CountTrie, count_nodes (how many nodes there are at and below a node), words_under (the words below a node, alphabetically), complete, ScanWords, syllable_words (n different made-up words of 2 to 4 syllables, each a consonant then a vowel, from a seeded generator), traced_bytes (the bytes still held when a build returns, from tracemalloc) and best_of (the smallest wall time of 3 runs) are written out in the answer.

A step is the unit of work each structure does for an operation, and it is counted on a counted copy that is checked to return the same answers as the plain code: for the trie a dict lookup (or a node taken off the stack by complete), for the sorted list a string comparison made by bisect_left or by sorted() (and a word read), for the set a hash or a word scanned. Counts do not change from run to run; times do.

  1. Check that the three structures answer alike, on the 241 lists of at most 2 strings of BED (BED holds every list of 0 to 3 strings, each 0 to 3 letters over "a" and "b", "" included) with each of the 40 PROBES (the strings of 0 to 3 letters over "a", "b", "c"), for membership, the prefix count and the completions with k of 0, 1 and 2. Count the empty list, a stored "", a single word, a word that is a proper prefix of another and a duplicate, and assert each was hit.
  2. Build 30,000 different syllable words, 10,000 membership probes (5,000 stored, 5,000 not stored) and 300 prefixes of 1 to 4 letters of stored words, build the three structures, and check they agree on every probe and prefix (the set's scans on 5 prefixes only, to keep the run short).
  3. Count the steps for each cell, and time each cell on plain code, each the smallest of 3 runs, in microseconds per operation (milliseconds for a whole job).
  4. Print the table: a row for each cell with the three structures as columns, and under each timed row the steps behind it.
  5. Print a verdict for a cell only when each of the other two structures is at least 2 times the best one (in time, or in bytes); print the ratio and no verdict for the sorted list against the trie on the prefix count, whose ratio does not stay at 3 when several copies of the answer run at once. End with a recommendation built from the verdict variables and the counts, never typed.
Q71End Flags And Walks That LieMediumMust Do

A trie stores a set of strings as a prefix tree. Each node has a children dict, mapping one character to the child node below it, and an end flag, which is True only where a stored word ends. A trie that walks to the right node can still give the wrong answer. Either the flag was set in the wrong place when the word went in, or the walk asks the wrong question when it gets there. A node that a walk reaches is not a word unless its flag says so. That is why search checks end. This question is about tries whose flags and walks are wrong in other ways.

The contract, for the correct Trie:

  • Any string may be stored, "" too. "" is stored by marking the root.
  • insert(word) returns True if the word was new and False if it was already stored. len() counts the distinct words.
  • search(word) is True only for a stored word.
  • starts_with(prefix) is True when some stored word begins with prefix, and a word equal to prefix counts. starts_with("") is True exactly when the trie holds at least one word.
  • delete(word) returns True if the word was stored and False otherwise, changing nothing. It cuts off nodes that no longer lead to a word.
  • _walk(s) follows the characters of s from the root. It returns the node reached, or None where the path breaks.

The oracle is ScanWords: the stored words in a Python set, with every prefix question answered by trying each word with str.startswith. The test beds are:

  • STRS: the 15 strings over "ab" of length 0 to 3.
  • BED: every list of 0 to 3 of them in every order, repeats allowed (3,616 lists).
  • PROBES: the 40 strings over "abc" of length 0 to 3.

These helpers are written out in the answer, along with two more. outline(node) lists every node below node as an indented line, with " *" where end is set. random_words(n, rng, alphabet, lo, hi) makes exactly n seeded random words of lo to hi characters, repeats allowed.

  1. Write four broken subclasses of Trie, each a small change to the correct code:
    • MarkEveryNodeTrie: its insert sets end on every node it passes.
    • MarkParentTrie: its insert keeps a parent beside node and marks the parent.
    • IndexWalkTrie: its _walk uses node.children[ch] instead of get.
    • ChildrenOnlyTrie: its starts_with asks only whether the node has children.
  2. Scan BED, sorted by number of strings and then by total characters. For each list, insert its words in order and compare each insert's return value and len() with ScanWords. Then compare search and starts_with on every probe. Count an exception as a failure. For each class, print the smallest failing list, the call that failed, the broken answer beside the truth, and how many lists fail. The correct Trie must fail none.
  3. Show that ChildrenOnlyTrie is not only wrong about "". Print its smallest failing list among the lists that do not hold "". Then insert "aa" into a MarkEveryNodeTrie and delete it. What does search("a") say now?
  4. Fuzz the correct Trie on 300 seeded scripts. Each script inserts a random list in its given, sorted or reverse-sorted order. It then deletes 8 stored or absent strings, and checks every probe after each delete. Count each case the fuzz hits: an empty trie, "" stored, a single word, a word that is a prefix of another, a duplicate insert, sorted and reverse-sorted order, and an absent delete. Catch Exception as a failure, and assert that every count is above 0.
  5. Build the closing line from the scan. Rebuild each class's smallest failing list and compare its outline with the correct Trie's. If the outlines differ, the class went wrong when the word went in. If they match, it went wrong when the word was looked up.
Q72Board Searches That Go WrongHard

Word search on a board was built earlier in this topic. A path starts at any cell and steps up, down, left or right, and it uses no cell twice. find_words(board, trie) walks from each cell with the trie node in hand. It marks the cell in a used grid before the recursive calls and unmarks it after them. It stops as soon as no stored word starts with the letters on the path. The oracle board_words(board, max_len) tries every ordered choice of cells with itertools.permutations and keeps the chains of neighbours, so it shares no code with the search. Here are five ways a student's search goes wrong. Each is find_words with one change:

  • find_no_mark has no used grid.
  • find_no_lower_bound tests nr < rows and nc < cols without 0 <=.
  • find_stop_at_word returns as soon as the path spells a stored word.
  • find_into_list collects the words in a list.
  • find_shared_rows builds the grid as [[False] * cols] * rows.
  1. Write the five broken searches.
  2. Build every board of 1 or 2 rows and 1 to 3 columns over "ab", smallest first (98 boards). Store every string over "ab" of 1 to 6 letters in the trie, so the truth on a board is everything board_words finds. Check that find_words matches it on every board.
  3. For each broken search, print its smallest failing board and what is extra, missing or repeated. Count the boards it fails on, and count those that raise. If a search's smallest failure is a wrong answer but other boards raise, print the smallest board that raises too.
  4. Show what the shared rows do on the smallest board where find_shared_rows fails: mark cell (0, 0) in each grid and print both. This is DSA Topic 2's grid trap.
  5. Fuzz find_words on 300 seeded boards with seeded dictionaries of 0 to 6 words, inserted in their given, sorted or reverse-sorted order. Count the cases: an empty trie, "" stored (never found on a board), a single word, a word that is a prefix of another, a duplicate insert, sorted and reverse-sorted order, words found, and words not on the board. Catch Exception as a failure.
Q73Deletes That Lose WordsMedium

Trie.delete was built earlier in this topic, along with its two bugs that cut too much or nothing at all. Here are three new ways to get it wrong. Each is the correct delete with one change:

  • CutIgnoringEndsTrie: on the way back up it cuts every node with no children, even a node where another word ends.
  • NoEndCheckTrie: it never checks that the walk ended on a stored word before unmarking it and counting down.
  • IndexDeleteTrie: it walks down with children[ch] instead of get.

A check is good only if the bug can show on its input, and the first of these bugs hides from the usual check.

  1. Write the three classes, and a run(cls, words, deletes) that inserts the words and then deletes the strings of deletes in order. After each delete, compare the return value, len(), search on every word of the list, and the node count with ScanWords. The right node count is the number of distinct prefixes of the stored words. Report the first disagreement, and treat an exception as one.
  2. From every list of BED, delete the 15 STRS in STRS order: "" first and shorter strings first, absent ones included. Print how many lists fail for each class and the smallest failure. Assert the exceptions by type name.
  3. Now delete each list's distinct words in every order. Print the smallest list and order where CutIgnoringEndsTrie loses a word. Show that the same list deleted shortest first passes.
  4. Show what NoEndCheckTrie does to len() on ["ab"] when you delete "a" and then "ab".
  5. Fuzz the correct delete on 300 seeded scripts (inserted in their given, sorted or reverse-sorted order, then 10 deletes of stored and absent words). Count the cases, a longer word deleted before its stored prefix included. Then check the lesson: does every failing order delete a longer word before its stored prefix?
Q74Prefix Counts That DriftMedium

In the counting trie from earlier in this topic, each node's words is the number of stored words at or below it. So count_prefix is one walk, and len() is the root's count. That counting trie was fuzzed through deletes with a recount of every node. Here are two new ways a count drifts:

  • RootlessCountTrie never adds 1 to the root on insert.
  • KeepZeroCountTrie's delete counts down but never cuts a node whose count reaches 0.

The second one keeps every count right. It is the shape that goes wrong, and lcp(trie) reads the shape: it walks down from the root while the node ends no word and has exactly one child.

  1. Write both classes. Write lcp_oracle(words), the common prefix of the smallest and largest word, and recount_ok(trie). recount_ok rebuilds every count from the end flags with no recursion, and it finds no node with count 0 below the root.
  2. On every list of BED, insert the words, then delete them in the same order. After every step, compare len(), count_prefix of every probe and lcp with ScanWords, then recount. Print each class's smallest failing list and what fails there.
  3. RootlessCountTrie's smallest failure holds "". Print its smallest failure without "", and say which probe is wrong.
  4. Insert "apple" into a KeepZeroCountTrie and delete it. Print len(), count_prefix("a"), lcp and recount_ok.
  5. Fuzz the correct CountTrie on 300 seeded scripts of 30 inserts and deletes over "ab" (in given, sorted or reverse-sorted order), with lcp checked and every node recounted after each step. Count the cases.
Q75Autocomplete That Skips Or RepeatsMedium

complete(trie, prefix, k) from earlier in this topic returns the stored words that start with prefix in alphabetical order. It returns the first k of them, all of them when k is None, and [] when k <= 0. It walks to the prefix's node and pops nodes from an explicit stack, pushing children in reverse sorted order, and stops once it has k words. Here are three off-by-one slips:

  • complete_past_k stops at len(out) > k.
  • complete_below_prefix starts the stack with the prefix node's children.
  • complete_no_guard leaves out the k <= 0 test.
  1. Write the three broken versions.
  2. Check the correct complete against ScanWords.complete on every list of BED, every probe, and k = None and -1 to 3. Then print each broken version's smallest failing list, prefix and k, beside the truth.
  3. complete_below_prefix's smallest failure is about "". Print its smallest failure on a list without "".
  4. Sort the three into "returns too many" and "skips a word", using their outputs.
  5. Fuzz the correct complete on 300 seeded lists over "abc" (in given, sorted or reverse-sorted order), with every probe and k from None and -1 to 5. Count the cases, k <= 0 and k below the number of matches included.
Q76Splitting A Radix EdgeHard

The radix tree built earlier in this topic came from compress, which folds every chain of nodes that have one child and end no word into one edge. Each edge carries a label. radix_search and radix_starts_with read it, and a prefix may end partway along an edge. To insert straight into a radix tree, find the child whose label starts with the word's next character, and compare the label with the rest of the word. If the two part inside the label, split the edge there: a new middle node takes the shared part, and the old child keeps the rest. Then go on below, or mark the end.

  1. Write radix_insert(root, word, splits=None). It returns True if the word was new and False if it was already stored, and "" marks the root. Also write radix_lines(root), an alphabetical listing of the labels with no recursion.

  2. Trace the inserts "team", "tea", "ten", "to", "toast", "t", and print the splits and the tree after each one.

  3. For every list of BED, insert in the list's order. Check each return value against ScanWords, every probe against the plain Trie, and the tree against compress of the finished Trie, line for line and node for node.

  4. Fuzz on 300 seeded scripts of 25 inserts over "abc" (in given, sorted or reverse-sorted order), checked after every insert. Count the cases and the splits.

  5. Write two broken lookups:

    • radix_search_first_char finds the child by its first character and skips the label without comparing it.
    • radix_starts_with_whole_edges requires every edge to fit inside the prefix.

    Print each one's smallest failing list and probe, beside the truth.

  6. Say in one line why delete is not built here.

Q77Edit-Distance-One BugsHard

One edit means: delete one character, insert one, replace one by a different one, or swap two adjacent different characters. edits1(word, alphabet) generates every string one edit away. one_edit(a, b) tests a pair directly. The two were proved to agree earlier in this topic, and the trie walk's same-letter replace was shown there too. Each definition is the oracle for the other. Here are four student slips:

  • edits1_gap_swap swaps word[i] and word[i + 2].
  • edits1_no_end_insert never inserts after the last character.
  • edits1_same_letter lets replace put back the same letter.
  • one_edit_any_swap accepts a swap of the first and last differing positions however far apart they are.
  1. Write the four broken versions.
  2. Take every pair of strings over "abc" of length 0 to 4 (121 strings, 14,641 pairs, by construction), smallest first. Check a generator against one_edit and the test against edits1. Print each one's smallest failing pair and how many pairs it gets wrong.
  3. For edits1_same_letter, check what its wrong pairs have in common.
  4. Assert that "aab" to "baa" is not one edit, and that one_edit_any_swap accepts it.
  5. Fuzz the correct pair inside the spell-check: near_by_edits (generate, then look up in a set) against near_brute (one_edit on every word). Use 300 seeded word lists over "abc" (in given, sorted or reverse-sorted order) and every query of 0 to 3 letters. Count the cases.
Q78Keys That Are Not Plain LettersEasy

Nothing in Trie cares what a character is. A children dict takes any hashable key, and a word can be any sequence of them.

  1. Store "New York", "new york", "R2D2", "2nd" and " pad". Print the root's keys, sorted, and say what order they come in. Then search with a different case.
  2. Store paths as tuples of parts, such as ("usr", "lib"), and query them. Then try to insert a list of lists, and assert the error by its type name.
  3. Write FoldOnInsertTrie, which folds case with str.casefold on insert only. Then write FoldedTrie, which folds on insert, search, starts_with and delete. Find FoldOnInsertTrie's smallest failure on lists of up to two of the 21 strings of length 0 to 2 over "aAbB", probing each of the 21, against a ScanWords of folded words. Check that FoldedTrie has none.
  4. Build characters beyond ASCII with chr() and print them with ascii():
    • Store "caf" + chr(233) and "stra" + chr(223) + "e", then search for the upper-case forms.
    • Compare lower() and casefold() on chr(223).
    • Print chr(233) is chr(233) and chr(300) is chr(300), and say what CPython does with one-character strings.
  5. Fuzz FoldedTrie on 300 seeded scripts over "aAbB" (in given, sorted or reverse-sorted order, then deleted in a seeded order with the case swapped). Count the cases, the same word in another case included.
Q79The Recursion That Runs Out On A Long WordEasy

words_under(node, path, out) from earlier in this topic lists every word below a node by recursing once per level. One stored word longer than the recursion limit is enough to break it. DSA Topic 14's recursive insert ran out the same way on keys inserted in sorted order.

  1. Store one word of 5,000 letters. Call words_under and catch the error. Print only its type name, and whether the word is longer than sys.getrecursionlimit().
  2. Run complete, count_nodes and outline on the same trie. They keep their own stack in a list. complete must return the word itself.
  3. compress recurses once per radix level. Show that it handles the long word (2 radix nodes). Then store the 3,000 nested words "a", "aa", โ€ฆ, by marking every node of one long word's path, and check that marking agrees with inserting every prefix on a short word. Show that compress fails on that chain while complete still returns the first 3 words.
  4. Fuzz words_under and complete against sorted(set(words)) on 300 seeded short lists (in given, sorted or reverse-sorted order). Count the cases.
Q80Changing The Trie While Walking ItEasy

delete_prefix(trie, prefix) removes every stored word that starts with prefix and returns how many went. The obvious version walks to the prefix's node and loops over node.children, deleting the words under each child as it goes. But delete cuts an emptied child out of that same dict, and Python refuses to go on iterating over a dict that has changed size.

  1. Write delete_prefix_live (the obvious version) and two fixes:
    • delete_prefix_keys_first loops over list(node.children).
    • delete_prefix_collect_first collects the words with complete, then deletes them.
  2. In one pass over every list of BED with every prefix in STRS plus "c" and "ac", compare all three with a scan. Print the live version's smallest failure (assert the exception by type name), how often it raises, and how many cases each fix matches.
  3. Show that a complete result is a new list, so deleting afterwards does not change it, while node.children is the live dict.
  4. Fuzz both fixes on 300 seeded lists over "abc" (in given, sorted or reverse-sorted order) with a seeded prefix. Count the cases.
Q81Accidentally Quadratic TriesHardMust Do

Code is accidentally quadratic when it is correct on every test and still does O(n^2) work over its input: nothing looks wrong until the input grows. Tries have three classic ways to do it. All three are shown here by counting (characters built, nodes visited, calls made), never by timing, because a count is the same on every run.

A trie stores words as paths from a root: each node has a children dict (one character to the child node) and an end flag that is True where a stored word ends. These helpers are written out in the answer: TrieNode, Trie (insert returns True for a new word; _walk(s) returns the node that the string s leads to, or None), count_nodes(node) (how many nodes there are at and below node), words_under(node, path, out) (appends every stored word at or below node to out, alphabetically; path is the list of characters from the root to node), complete(trie, prefix, k) (the first k stored words that start with prefix, alphabetically, found by an explicit stack that stops as soon as it has k; k <= 0 gives []), board_has(board, word, calls) (True when some path on the board spells word: it starts at any cell, each next cell is directly up, down, left or right of the one before, and no cell is used twice; calls is a one-item list that counts the calls of the recursive helper) and syllable_words(n, rng) (n different made-up words of 2 to 4 syllables, such as "kabalo", from a seeded random.Random).

  1. A string built at every node. words_under_concat(node, prefix, out, built) hands each child prefix + ch, so every node builds a new string as long as its depth. words_under keeps one list of characters and builds a string only where a word ends. Write both as counted copies that add the length of every string they build to built[0], and check they return the same words as words_under. First, for a trie holding one word of L letters with L = 50, 100 and 200, the strings built are L * (L + 1) / 2 the first way and L the second: assert both formulas. Then, on 3,000 syllable words, print the characters built both ways and the ratio, and assert that the first way equals the sum of the lengths of the distinct non-empty prefixes of the words.
  2. Collecting everything for the first k. first_k_by_sorting(trie, prefix, k, visits) walks every node below the prefix, collects every word, sorts them and keeps k. complete stops when it has k. Write complete as a counted copy too (visits[0] counts nodes taken off the stack) and check it returns what complete returns. On a trie of 10,000 syllable words with k = 10, and the prefixes "" and the first 1, 2 and 3 letters of the first word, print the nodes below the prefix, the nodes each way visits and the words the prefix has. Assert that the sorting way visits exactly the nodes below the prefix (checked with count_nodes) and that complete visits at most 1 + the letters, beyond the prefix, of the words it returns.
  3. Words that match all the way and still fail. A board is one row of L cells, every cell holding "a". The word "a" * (L + 1) is one letter longer than the board, and "a" * (L - 1) + "b" ends in a letter the board lacks. Every start cell matches every letter it reaches, so the search walks the whole board from each start. Count the calls of board_has on both words for L = 50, 100 and 200: they are L * L (predicted by formula; assert 2,500, 10,000 and 40,000), while the words "a" * k with k <= L are found after exactly k calls. board_has_guarded first counts letters (a Counter, DSA Topic 7): every letter of the word must appear on the board at least as often as in the word, otherwise it answers False without searching. Show its calls are 0 on both failing words and that it agrees with board_has on every word "a" * k for k from 1 to L. Then show with one more word (on a row of "a"s ending in "b", the word "a" * (L - 2) + "ba") that a word whose letters are all on the board but not on one path still pays for the search.

Every line printed is built from the counts. Say what each fix costs and what it saves, from the numbers.

Q82Memory Measured WrongMedium

How many bytes does a trie of 10,000 words take? Four easy-looking measurements go wrong, each for a different reason, and the last is repaired by adding what it left out. DSA Topic 13 already showed on a tree that sys.getsizeof counts one object and not what it points to, and that tracemalloc counts what a build keeps; this question applies both to a trie and finds what each shortcut leaves out.

The helpers TrieNode, Trie, count_nodes, syllable_words (n different made-up words from a seeded random.Random) and traced_bytes(build) (what build() allocates and still holds when it returns, measured with tracemalloc; make the inputs before calling it) are written out in the answer. Build the 10,000 syllable words first, then the trie, then measure:

  1. sys.getsizeof(trie) on an empty trie and on the full one. Print both.
  2. sys.getsizeof(set(words)) as "the size of the set". Print it beside the bytes of the 10,000 word strings the set points to (sys.getsizeof of each, summed).
  3. traced_bytes around a build that makes the words inside the measured call and returns the words together with the trie, so both are still alive when it ends. Print it beside the right call, traced_bytes(lambda: Trie(words)) with the words built before, and the extra bytes beside sys.getsizeof of the word list plus the 10,000 strings.
  4. Walk every node and add sys.getsizeof(node) alone, then add sys.getsizeof(node.children) too, and compare both with the right figure.

Print a table of the trie figures (the ones from steps 1, 3 and 4, and the right one) with the error of each against the right figure, per node and per word. Judge the set separately: against the cost of keeping its words alive, and against building it from words that already exist. Label each figure from its computed error ("within 5%" or "off by N%"), and build the closing lines from those labels.

Q83Bit Tries That Go WrongMedium

A bit trie for maximum xor (earlier in this topic) stores each number as a path of B bits, high bit first, where B is the bit length of the largest number, and for each x walks down preferring the child with the opposite bit. Two plausible mistakes keep it running and make it wrong. The contract of the correct function max_xor_bits(nums): the largest a ^ b over two numbers at different positions of a list of non-negative ints (equal values at two positions are a pair, xor 0); fewer than 2 numbers raises ValueError.

  1. Write max_xor_bits with a small BitNode (a two-slot list kids). The walk builds the xor bit by bit: at bit b it adds 1 << b when the opposite child exists and goes there, and otherwise takes the same-bit child.
  2. Write two broken functions: max_xor_narrow, which fixes the width at B = 3 "because the test numbers were small", and max_xor_low_first, which stores and walks the bits low bit first.
  3. Check all three against a brute force over every pair of positions (itertools.combinations) on every list of 0 to 4 numbers below 16, repeats and every order included (by construction 1 + 16 + 256 + 4,096 + 65,536 = 69,905 lists, 17 of them too short). Assert that the short lists raise ValueError (by type name) in all three, and that max_xor_bits is right on the rest.
  4. For each broken function, find by a scan in increasing size the smallest failing list and print it beside the truth and the wrong answer. Count the lists each one gets wrong, and say from counts what the failures have in common: every failing list of the narrow one holds a number needing more than 3 bits (assert it), and how many failing lists of the low-first one hold only numbers below 8.
Q84Tests That Never Share A PrefixHard

Random test data can be wrong in a quiet way: if the test words never share a prefix, a whole family of trie bugs cannot show. Two bugs of that family, each of which passes every test made of unrelated words:

  • Marks the end only on a new node (NewNodeEndTrie): insert sets the end flag only when it created at least one new node on the way down. A word that is a prefix of a stored word creates none, so it is never marked.
  • Counts only new nodes (NewNodeCountTrie): insert adds 1 to the word count of the nodes it creates, and leaves the counts of the nodes that already exist unchanged, so a second word through an existing node is not counted there.

The helpers TrieNode, Trie, CountNode, CountTrie, ScanWords (the oracle: a set, every prefix question answered by scanning with str.startswith), random_words(n, rng, alphabet, lo, hi) (exactly n random words) and syllable_words(n, rng) are written out in the answer, with BED (every list of 0 to 3 strings over "a" and "b").

  1. Write the two buggy classes as subclasses and the two tests a student would write. test_search(make, words) inserts the words and asserts every word is found. test_counts(make, words) inserts the words and compares count_prefix of every prefix of every word (and of "") with the oracle. Each test returns True when it catches a bug (an assertion or any other exception counts as caught).
  2. On 1,000 seeded lists of 5 random words of 3 to 8 letters from a to z, count how many lists catch each bug, and how many lists hold a word that is a proper prefix of another and how many hold two words with the same first letter. Assert that every list that catches the first bug holds a prefix pair, and print what the counts say about the second.
  3. Repeat on 1,000 seeded lists of 20 syllable words, then on 1,000 seeded lists of 5 words of 1 to 4 letters over "a" and "b" only.
  4. Run both tests on every list of BED, and print how many lists catch each bug. Find by a scan in increasing size the smallest failing list of each (for the first bug, also the smallest list that holds no empty word), beside the truth.
Q85The Suite For Any TrieHardMust Do

A test suite earns its keep when it fails on a broken trie. Write one suite that can check any trie class and show that it catches six planted bugs.

A trie here stores strings (the empty string "" is a legal word). Its contract, which the suite checks against a scan oracle (a Python set of the stored words, every prefix question answered by scanning it with str.startswith):

  • insert(word) returns True if the word was new and False if it was already stored. delete(word) returns True if it was stored and removed, and False, changing nothing, if it was absent (deleting "" is allowed when "" is stored). search(word) is True only for a stored word, not for a mere prefix. len(trie) is the number of distinct words stored.
  • A trie may also have starts_with(prefix) (True when some stored word begins with the prefix, a word equal to the prefix included) and count_prefix(prefix) (how many stored words begin with the prefix, a word equal to it included; "" counts every word). The suite checks each one only when the class has it.
  • complete(prefix, k) is a free function that takes the trie as its first argument: the first k stored words that start with the prefix, alphabetically, all of them when k is None, [] when k <= 0 or the prefix leads nowhere.

These helpers are written out in the answer: TrieNode, Trie (_walk(s) returns the node a string leads to, or None), CountNode, CountTrie (a trie whose nodes count the stored words at or below them, so count_prefix is one walk), complete, ScanWords (the scan oracle), and the lists STRS (the 15 strings over "a" and "b" of length 0 to 3), BED (every list of 0 to 3 of them, in every order, repeats allowed: 3,616 lists) and PROBES (the 40 strings over "a", "b" and "c" of length 0 to 3).

  1. Write check_trie(make, complete_fn=complete, stop_at_first=False), where make() returns a new empty trie. For every list of BED it inserts the words in order and compares each return value with the oracle, compares len, then compares search, starts_with and count_prefix (where present) complete_fn(trie, probe, 2) and complete_fn(trie, probe) (k None) for every probe of PROBES, then deletes all 15 strings of STRS in order, comparing each return value, len, and search afterwards. Any exception is caught and counts as a failure, naming its type. The result holds the number of lists run, the number of failures, the first failure as a sentence and the counts of the cases reached: empty list, list with "", list with a word that is a proper prefix of another, list with a duplicate, delete of an absent word, delete of "" when stored.
  2. Run it on Trie and on CountTrie: assert zero failures and that every case count is above 0, and print the counts.
  3. Plant six bugs and run the suite on each with stop_at_first=True, printing the first failure of each: a Trie whose delete leaves len unchanged; one whose delete returns True for an absent word; one whose insert returns True for a duplicate; complete that returns [] when k is None (a different complete_fn); a CountTrie whose count_prefix leaves out the word equal to the prefix; and a Trie whose delete("") refuses. Assert that every one is caught and say which list, in BED order, first exposes each.
Q86The Autocomplete ServiceMini-ProjectMust Do

Build the service behind a search box: a set of words, each with an integer weight (how popular it is), that answers "how many words start with this?" and "which are the best few?". Its contract, which every part of the answer must follow:

  • add(word, weight) stores a new word with that weight and returns True; if the word is already stored it changes nothing and returns False (a stored word's weight is changed with set_weight). The empty string "" is a legal word.
  • remove(word) returns True if the word was stored and is now gone, False (changing nothing) if it was absent.
  • set_weight(word, weight) replaces the weight of a stored word and returns True; for an absent word it changes nothing and returns False.
  • count(prefix) is how many stored words start with the prefix (a word equal to the prefix counts; "" counts every word), 0 when none do.
  • top(prefix, k) is the stored words that start with the prefix, highest weight first, ties broken alphabetically, at most k of them: [] when k <= 0 or no word starts with the prefix.
  • suggest_as_typed(text, k) is a list with one entry for each letter typed: entry i (from 1) is top(text[:i], k); the empty text gives [].
  • len(service) is the number of stored words.

Use a trie whose nodes keep the number of stored words at or below them (so count is one walk of len(prefix) steps, and a node whose count falls to 0 is cut off) and a word's weight at the node where it ends. Collect the words below a prefix with a walk and pick the best k with heapq.nsmallest over (-weight, word) pairs, which breaks ties alphabetically by itself. These helpers are written out in the answer: syllable_words(n, rng) (n different made-up words from a seeded random.Random) and best_of(fn) (the smallest wall time of 3 runs).

  1. Write the service and ScanService, a dict of word to weight with every question answered by scanning all the words (the oracle).
  2. Check 300 seeded scripts of 40 random operations on words of 0 to 4 letters over "a", "b" and "c", weights from 1 to 5 so ties happen. After every operation compare its return value with the oracle's, then compare len, count, top (with k from -1 to 4) and suggest_as_typed on two random probes. Count the cases reached (add new and duplicate, remove present and absent, set_weight present and absent, a top whose answer holds two equal weights, "" stored, k <= 0), assert each is above 0, and count any exception as a failure.
  3. On 10,000 syllable words with random weights from 1 to 1,000, take 200 prefixes of 2 to 4 letters cut from random stored words. Count nodes entered per top(prefix, 10) on a counted call (the timed code never counts), against the 10,000 words a scan reads. Then time plain count and top(prefix, 10) per query for the service and for the scan (the scan on the first 20 prefixes, divided by 20), each the smallest of 3 runs.
  4. For count, find the faster side (the service or the scan) from the two times, print slower / faster, name the faster side, and print a verdict only when that ratio is at least 2, otherwise "no verdict: within 2x". For top print the ratio alone, with no direction word, because it depends on how long the prefix is and moves with the load; let the nodes entered against the words read decide. Build the closing lines from the numbers.
Q87The Spell Checker On A TrieMini-Project

Build a spell checker whose dictionary is a trie and whose candidates are never generated. DSA Topic 7's spell checker made every one-edit string of a word (a letter deleted, two neighbours swapped, a letter replaced, a letter inserted), counted them, kept the ones that were stored words and ranked those by how often a corpus used them (a Counter). Here the trie is walked with one edit to spend, and only paths that exist in the trie are followed.

One edit means exactly one of: delete one character; insert one character; replace one character by a different one; swap two adjacent characters that differ. A word is never one edit from itself.

correct(trie, counts, word) returns:

  • [word] when the word itself is stored;
  • otherwise the stored words exactly one edit from word, most frequent first (counts[w] is how many times the corpus used w; ties are broken alphabetically);
  • otherwise []. The checker never looks at two edits: the general edit distance is DSA Topic 21, and no table is built here.

These helpers are written out in the answer: TrieNode, Trie, one_edit(a, b) (True when exactly one edit turns a into b), edits1(word, alphabet) (the set of strings one edit from word, inserting and replacing with letters of alphabet), near_by_edits(word, wordset, alphabet) (the stored words found by generating the candidates and probing a set), near_by_trie(trie, word, visits) (the stored words one edit away, found by walking the trie with one edit to spend; visits, if given, is a one-item list that counts every step from a node to a child), near_brute(word, words) (the oracle: one_edit on every word) and syllable_words(n, rng).

  1. Make a dictionary of 1,500 syllable words with a seeded random.Random, and a corpus of 20,000 tokens drawn from it with weights 1 / (rank + 1) (so a few words are common and most are rare); counts is a Counter of the corpus.
  2. Write correct, and correct_brute (same contract, built on near_brute and a set, never a trie).
  3. Make 500 seeded queries of four kinds: a stored word, a stored word with one random typo, a stored word with two random typos, and a random string of 4 to 8 letters. Check correct against correct_brute on all 500, and check that near_by_trie, near_by_edits (alphabet a to z) and near_brute agree on every query. Count what each answer was (the word itself, one or more candidates, nothing) and assert each is above 0.
  4. Count the trie's steps per query (on a counted call) against the number of candidates edits1 generates for the same word, print both averages and show three example queries with their ranked answers and counts. Say what the counts show about the work saved, and what the checker cannot do (two edits).
Q88The Boggle SolverMini-ProjectMust Do

Build a solver for a Boggle board. The board is a 4 x 4 grid of letters. A path starts at any cell and moves from a cell to any of its 8 neighbours (up, down, left, right and the four diagonals) that lies on the board, and no cell is used twice on one path. The path spells a word by reading its cells in order. A word counts when it is in the dictionary, is at least 3 letters long, and some path spells it. Each different word counts once, and its score depends on its length: 3 or 4 letters 1 point, 5 letters 2, 6 letters 3, 7 letters 5, 8 or more letters 11.

A trie stores the dictionary as paths from a root: each node has a children dict (one character to the child node) and an end flag that is True where a stored word ends. The search follows the trie as it follows a path, and stops a path as soon as no stored word starts with its letters. A used grid of True/False flags marks the cells on the current path: a cell is marked before the calls for its neighbours and unmarked after them.

These helpers are written out in the answer: TrieNode, Trie (insert(word) stores a word; _walk(s) returns the node that s leads to, or None), syllable_words(n, rng) (n different made-up words of 2 to 4 syllables from a seeded random.Random), syllable_board(rows, cols, rng) (a board whose cells alternate a consonant and a vowel, so it holds syllable words), boggle_words_perm(board, max_len) (the brute-force oracle: every string spelled by a path of 1 to max_len different cells, found by trying every ordered choice of cells with itertools.permutations and keeping the ones whose neighbours touch), boggle_has(board, word, calls) (True when some path spells word; calls, if given, is a one-item list that counts calls), find_boggle(board, trie, calls) (every stored word of 3 or more letters that some path spells, sorted; counts calls) and count_paths(board, max_len) (how many paths of each length 1 to max_len, with no trie at all).

  1. Write the helpers. The dictionary is 10,000 syllable words plus the 60 two-letter syllables (so the 3-letter minimum has something to drop).
  2. Check find_boggle against one boggle_has search per word on 50 seeded 4 x 4 syllable boards, using a dictionary of the first 600 words plus the 60 syllables, and count the two-letter words that a board spells and the minimum length drops (assert more than 0 over the 50 boards). Check both against boggle_words_perm on 20 seeded 3 x 3 boards (paths of up to 5 cells), with a dictionary made of every string the oracle found of 3 to 5 letters plus the syllable words of at most 5 letters.
  3. On 3 seeded 4 x 4 boards and the full dictionary, print the calls of find_boggle, the calls of one search per word and the paths of every length up to 8 cells (count_paths: the same on any 4 x 4 board, since it depends on the grid and not the letters), and show one board with its words, its score and its longest words.
  4. Say from the counts how much work the trie saves on a board, and how the saving compares with trying every path.
Q89The Command-Line CompleterMini-Project

A shell completes a command when you press Tab. Build the lookup behind it with a trie whose keys are whole words, not letters: the root's children are first words ("git", "ls", ...), a node's children are the words that may follow, and a node's end flag is True where a complete command ends (so "git branch" and "git branch delete" are both commands).

tab(commands, line) takes the text typed so far, whose words are separated by single spaces, and returns (new_line, shown). The words before the last are fixed and must follow a path in the trie; the last word may be empty (the line ends with a space) or partial. The matches are the words that can follow the fixed ones and start with the partial word, alphabetically.

  • No match (including a fixed word that is not in the trie): the line is unchanged and shown is [].
  • Exactly one match: the partial word becomes the match followed by one space, and shown is [].
  • Several matches: the partial word becomes the longest common prefix of the matches (no space), and shown is the list of matches.

These helpers are written out in the answer: TrieNode, Trie (a letter trie: insert(word) and the node walk) and lcp(trie) (the longest common prefix of the words stored in a letter trie: it walks down while the node ends no word and has exactly one child).

  1. Write CommandNode (a children dict from a word to a node, and end), CommandTrie(commands) (each command split on spaces), tab, and tab_scan, the oracle: it scans every command, and takes the longest common prefix of the matches from their smallest and largest string, never from a trie.
  2. Use 36 hand-written commands over git, cargo and a few single words (ls, less, list, cd, cat, cp). Check tab against tab_scan on every prefix of every command (every character position, so lines ending in a space are included), on 300 seeded lines made by changing one character of a command prefix, and on a few lines with an unknown fixed word. Count the cases (no match, one match, several matches with an extension of the typed word, several matches without) and assert each is above 0.
  3. Show one line of each kind with its result, and one short typing session where each Tab is followed by the next typed letters.
  4. Print the number of nodes of the word trie against the number of nodes a letter trie of the same lines would have (the lines, spaces included, in a Trie), and say what the word trie buys.
Q90The Search-As-You-Type BoxMini-Project

A search box shows suggestions after every keystroke: typing a letter adds it to the text, backspace removes the last one, and the box shows the 3 stored words with the highest weight that start with the text. Ties in weight are broken alphabetically, and an empty text shows the 3 best words overall. Fewer than 3 words may match; none gives []. Backspace on an empty text does nothing.

A trie stores the words, one node per distinct prefix. Here each node also keeps its best 3 words (as (-weight, word) pairs, smallest first, so heaviest first and alphabetical on a tie), filled while the words are inserted, so reading the suggestions costs nothing beyond finding the node. The box keeps a stack of nodes, one per typed letter plus the root: typing steps from the top node to a child, backspace pops. Once the text leaves the trie the stack holds None for every further letter, and a backspace back to a live prefix finds the node still on the stack.

These helpers are written out in the answer: syllable_words(n, rng) (n different made-up words from a seeded random.Random), best_of(fn) (the smallest wall time of 3 runs) and LETTERS (the 26 letters).

  1. Write TopNode and TopTrie(words_with_weights) with the cached best 3, SearchBox (type(ch) and backspace() both return the 3 suggestions; lookups, if given, is a one-item list that counts every child lookup) and suggest_from_root(trie, text, lookups), the way that walks the whole text from the root again after every keystroke.
  2. Write a session generator: 200 seeded sessions, each up to 20 keystrokes, typing the next letter of a chosen word 80% of the time and a random letter otherwise, and pressing backspace 30% of the time (also on an empty text).
  3. On a dictionary of 800 syllable words with weights from 1 to 20 (ties happen), check both ways against a scan (sorted over (-weight, word) of every word that starts with the text) at every keystroke of the 200 sessions. Count the cases reached (backspace on an empty text, a letter typed past the last live prefix, a backspace back from a dead text to a live prefix, a keystroke whose answer holds two equal weights) and assert each is above 0.
  4. On 10,000 syllable words with weights from 1 to 1,000, replay the same kind of 200 sessions. Count the child lookups of both ways on counted calls and assert the box's count is at most one per keystroke. Time both ways per keystroke on plain code (the smallest of 3 runs of the whole replay, divided by the keystrokes), print the ratio without a direction word (it is small and moves with the load), and let the counts decide.
Q91The Word Game HelperMini-Project

A word game deals you a rack of tiles: lowercase letters, plus at most one blank ? that stands for any one letter. A dictionary word can be played from the rack when every letter of the word takes its own tile: a tile showing that letter or, once, the blank. Tiles may be left over, and the empty word is never played. Write rack_words(trie, rack, calls=None), which returns the playable stored words in alphabetical order, each once; ValueError for a tile that is not a lowercase letter or ?, or for two blanks.

The walk is DSA Topic 8's permutations with repeats (a Counter of the letters left: take one, recurse, put it back), steered by the trie: from a node it steps only into children whose letter is still on the rack, or, when that letter has run out, onto the blank. So it never builds a string that no stored word starts with. calls, if given, is a one-item list that counts the calls of the recursive helper (one per node visited).

  1. Write rack_words and a scan to check it: rack_scan(words, rack) tests each distinct word with a Counter, counting how many of its letters the rack's letters cannot cover, and keeps it when that shortfall is at most the number of blanks. Show the ValueErrors, then play four racks against WORDS.
  2. Check rack_words against rack_scan on every list in BED with every rack over "a", "b" and "?" of 0 to 3 tiles that holds at most one blank, and on 300 seeded dictionaries of random words with repeats (letters "abcde", 0 to 5 letters) and racks of 0 to 7 tiles. Count the cases hit: empty dictionary, "" stored, a stored word that is a prefix of another, repeated words, racks with a blank, racks where the blank was needed, and racks that play nothing.
  3. The walk uses the blank for a letter only when no tile of that letter is left. Write rack_words_both, which also tries the blank while a real tile remains, check it returns the same words, and print the calls of each. Explain from the counts why trying the real tile first loses no word.
  4. Scale: 10,000 syllable words and 200 racks of 7 tiles (consonants and vowels in turn, a blank in every second rack). Print the nodes visited per rack (average and largest) against the trie's node count and against the words a scan must read, and say from the counts which does less work on every rack.
Q92The Text HighlighterMini-Project

A glossary holds phrases of one or more words ("new york", "york city hall"). Mark every glossary phrase in a text by wrapping it in brackets: "i love [new york] in may". Words are what str.split() gives, both for the phrases and the text, and are compared exactly; the output joins the words with single spaces. A phrase with no words is ignored.

The marking follows a stated rule: read the text left to right; at each word, if one or more phrases start there, mark the longest of them and continue after it; otherwise keep the word and move on one. So marks never overlap, and a word inside a marked phrase cannot start another one. Nothing here claims the rule marks as many words as possible; step 4 prints a case where it does not.

The trie is keyed by whole words, not letters: each edge is one word, so a node is a phrase prefix, and end says a whole phrase stops there. A dict of children takes any hashable key, so the trie code from earlier in this topic works unchanged on lists of words.

  1. Write PhraseTrie (add(phrase) returns whether the phrase was new; "" and all-space phrases are ignored and return False) and highlight(trie, text, lookups=None): from each word, walk the trie as far as the text's words allow, remembering the last position where a phrase ended. lookups, if given, counts the dict lookups. Show it on a short glossary and three texts.
  2. Write highlight_scan(phrases, text), the same rule by brute force: at each word, test every phrase (as a tuple of words) against the text's words at that position and keep the longest. Check that the two agree on every list in BED used as a glossary, each string read as a phrase of one-letter words ("ab" is the phrase "a b"), with every text of 0 to 5 words over "a" and "b", and on 300 seeded glossaries and texts of syllable words. Count the cases hit: empty glossary, an ignored empty phrase, a phrase that is a prefix of another, a repeated phrase, a text with no mark, and a text where the longest phrase won over a shorter one.
  3. On a glossary of 2,000 phrases (2 or 3 words from 300 syllable words) and a text of 20,000 words, count the lookups per text word against the word comparisons of the scan (on the first 1,000 words), and print both.
  4. Write highlight_shortest, the same walk that marks the shortest phrase at each word instead, and print a text where it marks more words than the stated rule, both outputs computed. Then say what the rule is and is not.
Q93The Dictionary PackerMini-Project

Ship a word list as one compact string. Build a trie, turn it into a radix tree with compress (every chain of nodes that have one child and end no word becomes one edge whose label is the chain's letters), and write that tree out in pre-order: for each node its label, a mark (! if a word ends there, : if not) and its number of children in decimal, children in alphabetical order. Labels are lowercase letters and only the root's is empty, so no separator is needed: a label ends at its mark, a count ends at the next letter. The root of ["car", "cart", "cat"] packs as :1ca:2r!1t!0t!0.

This is DSA Topic 13's N-ary serialisation by child counts (a value, then how many children follow, read back with a stack of nodes still owed children), applied to a radix tree. No json.

  1. Write pack(root) and load(text), both iterative. load raises ValueError on anything pack could not have written from a tree made by compress: a missing mark, a count with a leading zero, a label on the root, an empty label below it, a node below the root that ends no word and has fewer than 2 children (compress would have merged it or never made it), children out of alphabetical order or sharing a first letter, a node owed more children than the text holds, or text left over. Words must be lowercase letters (ValueError otherwise). Trace the pack of a small list.
  2. Round trip on every list in BED: load(pack(compress(trie))) holds exactly the distinct words (listed by a walk), answers radix_search and radix_starts_with like the trie on every probe in PROBES, and packs to the same string again.
  3. Damage the packed strings of 300 seeded lists: cut each one at every length, and change each of its characters in turn to each of !, :, 0, 1, a and b. Check every damaged string either raises ValueError or loads to a tree that packs back to exactly that string, which is also the packing of the words the tree holds. Count both outcomes and catch every other Exception as a failure.
  4. Round trip 10,000 words of three kinds (random letters, syllable words, words on shared stems) and print the packed length against the words joined by newlines, and the radix nodes against the trie nodes.
Q94The Router TableMini-Project

A router forwards each packet by the longest matching prefix. A route is "a.b.c.d/len" with a next hop, such as "10.1.0.0/16" -> "B": it matches every address whose first len bits (of 32, highest first) equal the route's. "0.0.0.0/0" matches everything (the default route) and /32 matches one address. When several routes match, the longest wins; when none does, the answer is None.

Store the routes in a binary trie over bits, like the bit trie earlier in this topic, but here a key is a variable-length prefix, not a whole number: a route of length len is a path of len steps from the root, each step one bit, and its next hop sits on the node where the path ends.

  1. Write parse_route(text) and parse_address(text) with str.split (ValueError unless there are four parts, each a whole number 0 to 255, with a length 0 to 32, and no bit set beyond the length), and a class RouteTable with add_route(route, hop) (returns True if the route is new; an existing route gets the new hop), remove_route(route) (returns whether it was there; nodes left with no route at or below them are cut off) and lookup(address, steps=None): walk at most 32 bits, remembering the hop of the last route passed. steps, if given, counts the bits walked. Show the errors and a small table.
  2. Write lookup_scan(routes, address), which tests every route with a shift and keeps the longest match. Check lookup against it on 2,000 seeded addresses for a table of 300 seeded routes (half of the addresses inside a route), then on 300 seeded scripts of adds, removes and lookups. Count the cases hit: the default route used, a /32 route used, no route matching, a longer route winning over a shorter one, a hop replaced, and removing an absent route. After every step, check the node count equals the distinct prefixes of the routes stored.
  3. Print the bits walked per lookup (average and largest, never above 32) against the routes the scan tests.
Q95The Path IndexMini-Project

Index the files of a project by path. A path is /-separated names such as "src/app/main.py": every name is non-empty, the last one is a file and the earlier ones are folders. Folders exist only while they hold a file, as in git. A path cannot be both a file and a folder: adding "src" when "src/app/main.py" is stored, or the other way round, raises ValueError, and so does an empty name ("a//b", "/a", ""). DSA Topic 13's file system kept a list of children per folder and noted that a dict of children keyed by name would be a trie: this is that trie, keyed by whole names instead of letters, with a file count in every node.

  1. Write PathIndex with add(path) (True if the file is new), remove(path) (True if it was a stored file; folders left empty are cut off), listing(folder) (the names directly inside a folder, sorted, each folder name ending in /; "" is the top; a folder that does not exist gives []), count_files(folder) (files at any depth below it, "" counts all) and deepest(path) (the longest leading part of a path that exists in the index, as a path string, "" when even the first name is missing). Show each on a small project, and the errors.
  2. Check every method against PathScan, which keeps the files as a set of name tuples and answers each question by scanning all of them, on 300 seeded scripts of adds, removes and queries over a few short names. Count the cases hit: an empty index, a duplicate add, an absent remove, a remove that cuts a folder, a file-against-folder clash, a query on a missing folder, and a deepest that stops partway.
  3. On 10,000 seeded paths of 2 to 6 names, count the dict lookups of count_files and listing per query against the tuples the scan reads.
Q96Explaining It ColdInterview

The interviewer says: "Explain a trie to me. I know Python dicts and sets, I have never seen a trie." Write the explanation as a program that prints it, where every claim is shown by something the program computes. Use the trie from earlier in this topic, written out in the answer.

  1. The tree of prefixes. Store "car", "card", "care", "cat" and "do"; print outline of the trie, and check that the nodes are exactly the distinct prefixes of the words, "" (the root) included.
  2. The end flag. Show that "ca" is a path but not a word (search False, starts_with True) while "car" is both, and that "car" ends at a node with children, so "a node with no children" cannot be the test for a word.
  3. One insert, traced. Insert "cart" with a traced copy of insert that prints, per character, whether it followed an existing child or made a new node, and check the traced copy leaves the same trie as the plain one.
  4. The three costs, each with a measurement on 10,000 syllable words: time per operation as dict lookups (a hit costs one lookup per letter; a miss stops at the first missing letter: print both averages over 1,000 probes each); nodes against characters; and bytes per word for the trie against a set (structure only, the strings built first).
  5. Where the alternatives win. One case for a set (its bytes per word against the trie's, from step 4) and one for a sorted list with bisect (the first 10 words with a prefix, timed against the trie's complete on 1,000 prefixes; a verdict only at a ratio of 2 or more). Close with the one-line summary, built from the numbers.
Q97Diagnosing By ReasoningInterview

An interviewer hands you five short functions, each with one bug, and asks you to find, by reasoning before running anything, the smallest input on which each gives a wrong answer. Then confirm each prediction by a scan.

  • D1 _walk written with node = node.children.get(ch, node): on a missing child it stays where it is instead of stopping.
  • D2 listing every word by a recursive pre-order walk over sorted children that appends each child's letter to a shared path list but never pops it off after the recursive call returns.
  • D3 a trie that remembers each prefix starts_with said True for, in a set, and answers from that set next time; delete does not clear it.
  • D4 compress that also folds the root into its only child when the root ends no word, so the root gets a non-empty label.
  • D5 one_edit that returns False unless the lengths differ by exactly 1 (one edit is a delete, an insert, a replace by a different character or a swap of two adjacent different characters).

"Smallest" means: for D1 to D4, the first list in BED (every list of 0 to 3 strings over "a" and "b", shortest lists first) on which the function disagrees with the correct one on some probe in PROBES (for D3, after deleting each stored word in turn and probing again); for D5, the first pair of strings over "a" and "b" of length 0 to 3, ordered by total length, then alphabetically, where it disagrees with the correct one_edit.

  1. Write each prediction with its reason before the scans run (as data in the program, printed first).
  2. Write each buggy function beside the correct one, scan, print the first failure next to the truth, and assert the scan found exactly the predicted input.
Q98Designing For QueriesInterview

"Our dictionary service holds 10,000 words. Of every 100 queries, 70 ask whether a word is stored, 20 count the words with a prefix, 9 ask for the first 5 words with a prefix (alphabetically), and 1 asks for the stored words one edit from a misspelling. Which structures would you keep in memory?" Answer by prototyping and measuring, not by opinion. The candidates are a set, a sorted list with bisect (DSA Topic 3), and a counting trie (CountTrie, a count of the words below each node), all written out in the answer; one edit is a delete, an insert, a replace by a different letter or a swap of two adjacent different letters.

  1. Build all three from 10,000 syllable words and measure their bytes per word, structure only (the strings built first), with traced_bytes.
  2. For each operation, check the candidate ways agree, then count their work and time them: membership (set in against trie search), prefix counts (two bisect_left calls, counting string comparisons in a counted copy, against the trie's lookups), the first 5 words (a slice of the sorted list against complete), and one-edit suggestions (generating every candidate and probing the set against walking the trie: candidates against steps). A timing verdict needs a ratio of at least 2, and the winner is whichever is smaller. For prefix counts and one edit, the gap moves from run to run when other programs share the machine (sometimes under 2x), so print those ratios alone and let the counts decide.
  3. Pick a structure per operation from step 2, take the set of structures those picks need, and check it against two memory budgets: 1,000 and 300 bytes per word. When the picks do not fit, drop the trie, serve its operations from the set and the sorted list, and print what that costs in counted work. Print the estimated time per 1,000 mixed queries of each design (ratio only).
Q99The Mock Interview: Palindrome PairsInterview

The mock interview question: "Given a list of words, return every pair of positions (i, j) with i != j such that words[i] + words[j] is a palindrome." Positions, not words: a list may repeat a word, and each copy counts. The empty string is a word like any other: "" + w and w + "" are palindromes exactly when w is, so "" pairs both ways with every palindrome at another position (another "" included). Return the pairs sorted.

  1. Brute force first. Try every ordered pair and test the joined string: O(n^2 * L) for n words of up to L letters. Count the palindrome tests.
  2. Then a trie of reversed words. Insert each word reversed; at each node on the way, note the words whose rest (the part of the reversed word still below that node) is a palindrome, and at the end node, the word itself. To answer for words[i], walk its letters down the trie: whenever the walk passes the end of some reversed words[j] before words[i] runs out, the pair works when the rest of words[i] is a palindrome; when words[i] runs out at a node, every word noted there pairs with it. Test the rest of words[i] once per node, however many words end there, so repeated words cost no extra tests. Explain in two lines why every pair is found exactly once, and count the palindrome tests (those made while building included).
  3. Check the two on every list in BED and on 300 seeded lists of up to 12 words over "a" and "b" (0 to 4 letters, repeats allowed). Count the cases hit: an empty list, "" present, "" twice, a repeated word, a word that is a prefix of another, and a list with no pair.
  4. Print the palindrome tests of both for 200, 400 and 800 seeded different words of 3 to 8 letters over "abc", and say from the counts how each grows when n doubles.
Q100CapstoneInterviewMust Do

"Build the dictionary service for a word game." The dictionary is 10,000 made-up words, each 2 to 4 syllables of a consonant then a vowel ("kalo", "bitesu"), and each word has a whole-number weight (how often players use it). Words are strings of lowercase letters; the empty string "" is a word like any other. The service answers six requests, and these are its contracts:

  • contains(w): True exactly when w is stored.
  • count_prefix(p): how many stored words start with p (a word equal to p counts; "" counts every word; 0 on an empty dictionary).
  • top(p, k): the k stored words starting with p that have the highest weight, highest first, ties broken by the word alphabetically; fewer if fewer match; [] when k <= 0 or nothing matches.
  • suggest(w): the stored words exactly one edit from w, sorted. One edit is: delete one letter, insert one letter, replace one letter by a different one, or swap two adjacent different letters. w itself never counts, and two or more edits are out of scope (the general edit distance needs a table, DSA Topic 21).
  • on_board(board): every stored word spelled by a path on a board of letters (a list of rows of one-letter strings), sorted. A path starts at any cell, steps up, down, left or right, and uses no cell twice; "" is never found.
  • a memory report: bytes per word of the structure, the strings themselves not counted.

The design is a counting trie: a tree of nodes with one letter per edge, where the path from the root to a node spells a prefix, each node has a dict of children, a flag saying whether a word ends there and a count of the words ending at or below it. These helpers are written out in the answer: CountNode and CountTrie (the counting trie: insert, search, count_prefix and _walk, which returns the node a string leads to, or None; its docstring compares it with Trie, the same tree without counts, which this answer does not need); words_under (every word below a node, alphabetically); near_by_trie (walks the trie spending the single edit at each position); find_words (one walk from each cell carrying a trie node: it marks a cell used before stepping on and unmarks it after, and stops as soon as no stored word starts with the letters on the path); and the checks: ScanWords (the words in a Python set, every prefix question answered by testing every word with str.startswith), one_edit(a, b) (the edit rule tested directly), edits1 (every string one edit away), near_by_edits (generates those strings and keeps the stored ones), near_brute (one_edit on every word), board_has (a search for one word from every cell), board_words (every string a path spells, by trying every ordered choice of cells with itertools.permutations), syllable_words, syllable_board (a board in the same syllable pattern), traced_bytes (bytes held by what a function builds, with tracemalloc) and best_of (the smallest time of 3 runs).

  1. Write WordService, stating each method's time and space. Show the contracts on a small dictionary: an empty one, one holding "", k <= 0, a prefix nothing starts with, and a word with no neighbour.
  2. Validate every request on the 10,000-word service against its check: contains and count_prefix against ScanWords (2,000 words, half stored; 300 prefixes of 0 to 4 letters), top against sorting every match by (weight descending, word) for k = 0, 1, 5 and 50, suggest against near_brute on 40 misspelled words, on_board on a 5 x 5 board against board_has run for every stored word, and on 10 boards of 3 x 3 against board_words (paths of up to 5 letters, so the words of up to 5 letters).
  3. Report the memory: bytes per word for the trie and the weights, against a set and a sorted list of the same words.
  4. Do the same requests with a set and with a sorted list (two bisect_left calls for a prefix's range, as in DSA Topic 3): membership with a set; counting by two bisect_left calls and by a set scan; top from the sorted range; suggest by generating every one-edit string and probing the set; on_board by searching for each word separately. Count the work where it can be counted (dict lookups against string comparisons; for top, the trie's lookups and nodes walked below the prefix plus the matches heaped, against the two bisects' comparisons plus the matches sliced; steps against generated strings; search calls) on counted copies, and time the plain code. A timing verdict needs a ratio of at least 2 and goes to the faster side; for counting with bisect, for top and for suggest, whose gaps move from run to run when other programs share the machine (sometimes under 2x), print the ratio alone and let the counts decide.
  5. Build the closing recommendation, one line per request, from the verdicts and counts of step 4, and the memory line from step 3.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session