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.
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.
- Write out
LETTERS(the 26 lowercase letters) andWORDS(24 short words, written in the answer, several of them prefixes of others such as"a","an","and"). - Write
prefixes_of(words): a set of every prefix of every word inwords,""and each whole word included. - 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. - Assert
nodes <= characters + 1onWORDS, 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. - Print how many nodes one separate path per word would need, against how many the shared paths need, and the difference.
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.
- Write
TrieNodewith__slots__ = ("children", "end"), an emptychildrendict andend = False. - Write
link_word(root, word): walkwordfromrootone character at a time, creating a missing child with a newTrieNode, and setend = Trueon the last node. (No trie class yet: this is a plain function.) - Write
outline(node), which returns the trie belownodeas 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. - 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. - Print the keys of the dict at the root, at the node for
"ca"and at the node for"car", with each node'sendflag, and assert that aTrieNodehas only the two slots (no character). - 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).
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").
- Write
TrieNodeandTriewith__init__(words=()),__len__andinsert. - Trace
inserton"car","card"and"cat": after each, print what it returned,lenand the node count, then the outline. - Build the three beds (assert their sizes by construction: 15, 3,616 and 40).
- 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, thatcount_nodes(root)equals the number of distinct prefixes (the root counted), and thatlen(trie)equals the number of distinct words. - Show a broken
insertthat always makes a new child (node.children[ch] = TrieNode()) and so throws away what hung below. Find, by scanningBEDin order, the first list where itslenis wrong, and the first list wherelenis right but the outline is wrong, and print each beside the truth.
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").
- Write the
TrieNode,Trie(with__init__,__len__,insert,_walk,searchandstarts_with) and the beds. - Write the brute-force oracle
ScanWords: a Pythonsetof the stored words, wheresearchisword in setandstarts_withscans every stored word withstr.startswith. - On every list of
BEDand every probe ofPROBES, assert thatsearchandstarts_withof the trie equal those ofScanWords, and that when_walkreturnsNoneboth answers are False. Count the probe checks: 3,616 lists times 40 probes, by construction. - Show a broken
starts_withthat returnsnode.end(it only accepts a prefix that is itself a word). ScanBEDin order, each list with every probe in order, for the first failing pair, print it beside the truth, and count the failing pairs. - Print
starts_withandsearchfor"ap","app"and"apple"on a trie holding"apple".
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.
- Write
TrieNode,Trie(__init__,__len__,insert,_walk,search) and the beds. The oracle for a probe isprobe in set(words). - 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). - For each, scan
BEDin order, each list with every probe in order: print the first failing (list, probe) beside the truth, and count the failing pairs and lists. - 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. - 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.
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.
- Print a table of four cases (the empty trie, a trie of
["a"], of[""]and of["", "a"]) againstsearch(""),starts_with(""),lenand the node count. Assert each cell against the contract. - Assert that storing
""in the trie of["a"]returns True, changeslenby 1 and the node count by 0. - 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 checksearchandstarts_withagainst a set andstr.startswithfor every list and every probe ofPROBES(the 40 strings of length 0 to 3 over"abc"). - A student writes
starts_with(p)as_walk(p) is not None. ScanBEDandPROBESin order, print the first failing pair beside the truth, and assert that the failing pairs are exactly the empty list with the probe"".
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.
- 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 thatlenand the node count are unchanged. Print how many such lists there are (660 by construction). - Show a broken
insertwhose size counter adds 1 on every call. Find, by scanningBEDin order, the first list where itslenis wrong, print it beside the truth, and assert that the failing lists are exactly the lists with a repeat. - 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 equalslenandlen(set(stream)).
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.
- Show the four
ValueErrorcases once, asserting the exception by its type name, and assert that a valid call returns exactlynwords. - 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. - 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 aCounter, print the counts in order and assert that no miss cost more than 8 lookups. - 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.
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).
- 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. - Write an oracle
oracle_shape(words)from the set of distinct prefixes and the set of distinct words alone. - Assert on every list of
BEDthat the two agree, that the height equals the longest word's length (0 when there is none), and that leaves plus inner words equallen(set(words)). - 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.
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.
- 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 withwords_under, and assert that the result equalssorted(WORDS). - Write a variant
words_under_unsortedthat loops overnode.childrendirectly. Run both on the words["pear", "apple", "plum", "peach", "apricot"], print both orders, and assert that they differ. - 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 thatwords_underequalssorted(set(words))and thatpathis empty afterwards. - Show a broken
words_under_postthat appends the node's word after its children. ScanBEDin 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.
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
Trueand removes the word when the word is stored, andFalsewith 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"}isFalse). - 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).
- Write
deleteand trace it on["app", "apple", "apt"]: printoutlineafter each ofdelete("apple"),delete("ap"),delete("app"),delete("apt"), with each return value. - 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 inSTRS): build the trie, then delete each of the 15 strings in turn, once in the order ofSTRS(shortest first) and once in reverse (longest first). After every delete compare withScanWords: the return value,len, the listing fromwords_under, no dead node, andcount_nodesequal 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. - A student cuts the end node from its parent even when it still has children below (
ForgetsChildrenTriein the code). Find, by a search in increasing size, the smallest list and word where it breaks, and print its result beside the truth.
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).
- Write
FlagOnlyTrie, aTriewhosedeleteonly clears the flag and fixeslen(namedFlagOnlyTriein the code). - Over every list in
BEDof at most 2 strings (241 lists over "a" and "b", repeats and""included), delete each of the 15 strings inSTRSfrom aFlagOnlyTrieand comparesearchandstarts_withon every probe inPROBESwithScanWords. Count how often each of the two disagrees, and print the first list, word deleted and probe wherestarts_withlies, beside the truth, for the empty probe and for a non-empty probe. - A dead branch also costs memory. Insert 1,000 random words, delete every one of them, and print how many nodes are left in
FlagOnlyTrieand inTrie.
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.
- 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. - Check it against
ScanWords.count_prefixon every list inBED(0 to 3 strings over "a" and "b", repeats and""included) with every probe inPROBES. - 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.
- A student counts the nodes under the prefix instead of the words that end there (
count_nodes_not_wordsin the code). Find the smallest list and probe where it differs from the truth.
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 towordson every node of its path (the root included). It returnsTrue; a word already stored changes nothing and returnsFalse, 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 withprefix: 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).
- Write the classes and trace
count_prefixon["app", "apple", "apply", "apt", "bat"]for the prefixes"","a","ap","app","apple","b"and"z". - Check
count_prefixon every list inBED(3,616 lists of 0 to 3 strings over "a" and "b", repeats and""included) with every probe inPROBES(the 40 strings of length 0 to 3 over "a", "b" and "c"), againstScanWords. Also check that the lookups made by onecount_prefixcall equallen(prefix)or fewer, using a copy of the walk that counts them. - A student skips the search in
insertand always adds 1 along the path (NoCheckCountTriein the code). Find, by a search in increasing size, the smallest list where it counts wrongly, and print the result beside the truth. - The extra field is one int in every node. What that costs in bytes is measured later in this topic.
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.
- Paste
CountTrieand writerecount_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'swords. It must also find no node withwords == 0below the root. - Fuzz 300 seeded scripts of 40 steps each over the alphabet "abc" (words of 0 to 4 letters):
insert,delete, andcount_prefixqueries chosen by the seeded generator, compared withScanWords. After every step runrecount_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), catchExceptionas 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. - A student subtracts 1 along the path before checking that the word is stored (
SubtractFirstCountTriein 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.
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 toprefixis one of them), in alphabetical order, and a word appears once; k=Nonereturns every such word;k <= 0returns[];klarger 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
kwords, 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).
- Write
completeand trace it on["bat", "bath", "bathe", "be", "bean", "car"]for prefix"ba"withk= None, 2 and 0, and for"x". - 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 inPROBES(40 strings over "a", "b", "c" of length 0 to 3) andkinNone, 0, 1, 2, 5, againstScanWords.complete. - Count the nodes
completepops against the whole subtree below the prefix, on 10,000 random syllable words (2 to 4 syllables of a consonant and a vowel) withk = 10, for the most common prefixes of length 1, 2 and 3. Use a counted copy and check that it returns the same words ascomplete. - The flat alternative, a sorted list searched with two
bisect_leftcalls (DSA Topic 3's autocomplete), is timed against this later in this topic. - A student pushes the children in sorted order, not reverse (
complete_forwardin the code). Find the smallest list and prefix where the result is wrong, and print it beside the truth.
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 oflotohiletters fromalphabet;syllable_words(n, rng): n different made-up words of 2 to 4 syllables, each a consonant then a vowel (SYLLABLEShas the 60 of them), such as"kabelo";prefixed_words(n, rng, stems, lo, hi): n different words that each start with one ofSTEMS("counter","electro", ...) followed bylotohiletters.
- Write the builders and show each raising
ValueErroron a bad request (assert the exception's type name). - 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). - State from the numbers which list shares most, and whether sharing grows with n.
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.
- 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 newTrieand assert theoutlineis identical for every order of the same k words. Count the orders tried. - The dicts inside the nodes do remember insertion order, so the raw
childrenof the root are not always in the same order. Count, for k = 6, how many different root orders appeared, and show whyoutlinehides it (it sorts the keys).
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.
- Write
nd_insert,nd_search,nd_starts_with,nd_words(root, prefix)(the stored words that start withprefix, alphabetically, iterative with a stack) andnd_count_prefix. Check them on every list inBED(0 to 3 strings over "a" and "b", repeats and""included) with every probe inPROBESagainstScanWordsand againstTrie. - For 10,000 distinct random words (3 to 10 letters over a to z) build a
Trieand a nested-dict trie and print the bytes each holds, per word and per node. Time both builds withbest_ofand print the ratio, with no verdict. - A student uses
Noneas the end key (B19 in the code).nd_searchstill works. Find the smallest list where the alphabetical listing fails and print the exception's type name.
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).
- Write
build(words, end),search(root, word, end)andstarts_with(root, prefix)for a nested-dict trie whose end key isend(end -> Trueinside the node), and show B20: withend = "$", find, for the alphabet "a$", the smallest list wheresearchreturns 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). - 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 objectEND = 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. - 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.
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.
- Write
ArrayNode(a listslotsof 26Noneentries and anendflag) andslot(ch), which returnsord(ch) - 97and raisesValueErrorfor anything but a lowercase letter. Writearray_insert,array_searchandarray_starts_withon 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. - 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. - Show the student bug: no range check, so
slotis justord(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.
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.
- Write
rinsert(node, word, i=0), which returnsTrueif the word was new andFalseif it was already stored, andrsearch(node, word, i=0, calls=None), which counts its calls in the one-item listcallswhen 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 thanlen(probe) + 1calls. - 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.
- Show the student bug of
rsearchthat calls itself but does notreturnthe answer. Find the smallest failing list and probe by a scan, and print it beside the truth.
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.
- Write
build_reversed(words)(a trie of every word written backwards),ends_with(rtrie, suffix)(reverse the suffix, then askstarts_with) andwords_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, againststr.endswithon every distinct word. The empty suffix ends every word. - 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". - 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.
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.
- Write
nodes_per_level(trie)that returns a list whose entrydis the number of nodes at depthd(the root is depth 0). Walk one level at a time with adeque(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 ofWORDS(printed by level). - 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 exceeds26^d. - 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.
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).
- Write
starts_with_counted(trie, prefix, lookups), which answers likestarts_withand adds one tolookups[0]for every dict lookup it makes. Writecount_containing(trie, sub, visits), which walks every node and counts the stored words that containsubanywhere, adding one tovisits[0]per node; andany_containing, which does the same walk but stops at the first word that containssub. - 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,endswithandinon the words. - From the printed counts: the most lookups a prefix question needed, the nodes a substring count needed, how soon
any_containingstopped 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.
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".
- 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. - Write two oracles that use no trie: a column scan (position
iis kept while every word is longer thaniand 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 fromrandom.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. - 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". - 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.
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.
- Collect the words under the prefix with
complete, then pick the topkwithheapq.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 ofk. - 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 atk. Checkrankedagainst 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) andk= 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,kabove the matches, an absent prefix), assert each is above 0, and count an exception as a failure. - 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 (whichcompletevisits all of, by construction), the words collected and the words returned. Say in one line what would avoid the collection. - 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.
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.
- Write
random_board(rows, cols, rng, letters)andsyllable_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 raisingValueErroron a bad request. Writeboard_words(board, max_len), an oracle that shares no code with the search: the set of every string spelled by a path of 1 tomax_lencells, found by trying every ordered choice of cells withitertools.permutationsand keeping those whose neighbours touch. - 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 incallswhen 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. - Check
board_hasagainstboard_wordson 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. - 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.
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.
- Write
search_each(board, words, calls): the words for whichboard_hasis true, with one shared call counter. - 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. - 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.
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 [].
- Check
find_wordson 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 bothboard_wordsand oneboard_hasper word. - 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; oneboard_hasper 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 asevery_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. - 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".
- 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.
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.
- 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. - Check
one_editagainstedits1on 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 pairone_edit(a, b)must equalb in edits1(a, "abc"); also count the pairs that are one edit apart and check thatone_editis symmetric. - Check the distinct count by formula. For a word of L >= 1 letters with no two equal neighbours,
edits1(word, LETTERS)has52L + 25strings, and the empty word has 26. Check it for L = 1 to 9. Build the list of candidates with repeats kept inraw_edits1and show where the difference comes from. Then show that equal neighbours lower the count. - 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.) - 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.
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.
near_by_edits(word, wordset, alphabet): generate every candidate withedits1and keep the ones inwordset(a set of stored words).near_by_trie(trie, word, visits=None): walkworddown the trie. At each position spend the single edit every possible way (deleteword[i]; insert any child's character; replaceword[i]by a different child's character; swapword[i]andword[i + 1]), then follow the rest ofwordexactly. 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.near_brute(word, words): the oracle, which tests every word of the list withone_edit.- Check that all three agree on every third list of
BEDwith every probe inPROBES, 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. - 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_trietakes against the distinct candidatesedits1builds. Check every result againstnear_brute. Decide from the counts, not from a clock, and build the closing line from them. - A student's replace step also allows the same character, which spends no edit (
near_by_trie_same_replacein the code). Find the smallest list and probe where it disagrees withnear_brute, with a plain search, and print both answers.
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.
- Write
compress(node, label=""), which builds a new radix tree holding the same words as the trie belownodeand leaves the trie unchanged. It recurses once per radix level, so its depth is at most the longest word. Writeradix_search(root, word)(True whenworditself is stored) andradix_starts_with(root, prefix)(True when some stored word begins withprefix; the prefix may end partway along an edge; the empty prefix is True exactly when at least one word is stored). - 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.
- Check the radix tree against the plain
Trieon every list inBEDwith every probe inPROBES, forsearchand forstarts_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. - 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. - 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. - A student folds a chain even when a word ends inside it, as
compress_through_endsin the code. Find the smallest list where it disagrees withTrie, with a plain search, and print both answers.
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.
- 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)andsorted(words), and the strings' own bytes, each as bytes per word. - 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.
- Explain the trie's cost from measurements: the bytes per node (measured, and the nodes counted), against the
sys.getsizeofof 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. - 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-trieanddatrieare named only: they keep their nodes in arrays rather than in Python objects.
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).
- 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. - Write the oracle
replace_scan, which sorts the roots by(length, root)and takes the first one thatstr.startswithaccepts. - Check both on the sentence in the opening example, on roots
[""](ValueError, asserted by type name), on every list inBEDthat holds no""with a sentence of every non-empty probe, and on 200 seeded cases. Count what the checks covered. - 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.
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).
- Write
SumNode(a dictchildrenand atotal) andMapSumwith a dictvalues(key to its current value) and a trie whose every node stores the sum of the values of the keys at or below it.insertcomputesvalue - 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.totalis one walk. - Write the oracle
DictSum, which keeps a plain dict and answerstotalby scanning every key withstr.startswith. - 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. - 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.
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).
- 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'sendflag.visits, if given, is a one-item list that counts every call. The recursion is as deep as the pattern is long. - Write the oracle
scan_match(words, pattern), which tests every stored word character by character. - Check them on every list in
BEDwith 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. - 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.
- 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.
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).
- 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. - Write the oracle
buildable_by_set, which puts the words in asetand tests every prefix of every word. - 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. - 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.
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).
- Write
prefix_free(entries), which inserts the entries one at a time into a trie ofTrieNodes 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. - Write the oracle
prefix_free_sorted: sort the entries, then compare neighbours withstartswith. Why neighbours suffice: ifais a prefix ofcthen every stringswitha <= s <= cin sorted order starts withaas well, so the entry right afteradoes. Write also the plainest oracle,prefix_free_pairs, which tests every ordered pair, and check that the neighbour method agrees with it. - Check all three on the phone-number example, on every list in
BEDand 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. - 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.
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).
- Write
shortest_unique_prefixes(words): build aCountTrie, 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. - Write the oracle
unique_by_scan, which for each distinct word tries prefixes by length and counts the distinct words that start with each, withstr.startswith. - Check them on the example, on every list in
BEDthat 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.
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.
- 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.
- 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 isNonewhile not counting). - 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 thatvisitsis at most the number of letter-string prefixes the digits could spell (the sum of the products of the firstikeys' letter counts). - 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
BEDwith 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. - A student never checks the digits (B41 in the code). Find the first digit that raises
KeyErrorand print it beside the contract'sValueError. Show that a dead path hides the bad digit.
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.
- Write
complete_from(node, prefix, k)(the earlier completion, started at a node) andsuggestions, with alookupslist that gets one item per letter, and trace one session on 2,000 syllable words. - 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. - Check the first 241 lists of
BED(0 to 2 strings) with each of the 40PROBEStyped 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. - 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
BEDandPROBES, and print it beside the truth.
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 returnsTrue; it returnsFalse, 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 exactlyword(0 if none), andcount_prefix(prefix)is the copies that start withprefix(a copy equal to the prefix counts,""counts all). Both are one walk.lenis the copies stored in all.
- Write the class and trace six inserts and three erases.
- 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 acollections.Counter(the oracle:count_prefixscans every key withstartswith): 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. - A student's
eraseremoves every copy (B43 in the code). Find, by a search overBEDandSTRS, the smallest list and word where it differs from theCounter, and print both.
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.
- Write the class, and
ScanChecker(the naive version and the oracle: keep the text, test each word withendswith). Feed both a stream of 3,000 letters (1,500 random syllables) against 400 syllable words. Count the trie steps (a one-item liststepsthat isNonewhile not counting) and assert that no letter took more thanLmax. Print the steps per letter against theendswithtests per letter. - 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. - A student's buffer is one letter short (B44 in the code). Find, by a search over
BEDand 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.
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.
- Write
leaves(trie, flip),encode(words)(it returns the encoding and the kept words), and the oracleencode_scan(test every pair withendswith). Trace["time", "me", "bell", "ell", "me"]. - 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. - 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.
- A student builds the trie of the words as written, forward, and keeps its leaves (B45 in the code). Find the smallest list in
BEDwhere it differs, and show that its entries do not cover every word.
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.
- Check the claim on every pair of the 121 strings over "a", "b" and "c" of 0 to 4 letters, with
startswithandendswithas the oracle. - Write
count_by_key(words, key),count_pairs(pair keys) and the oraclecount_scan. Trace a small list. - Check every list in
BEDand 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. - 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.
- 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
BEDwhere it differs and print it beside the truth.
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.
- Write
lex_order(n)with astepscounter (a one-item list,Nonewhile not counting) and tracen = 13andn = 100. - Check against
sorted(range(1, n + 1), key=str)for everynfrom 0 to 300, around each power of ten up to 2,000 and for 30 seeded largern. Assert the steps are at most2 * n + 1, and print the most steps per number. - Show that a
Trieof the strings"1"to"n", read withwords_under, gives the same list. - A student walks the same tree with roots 0 to 9 (B47 in the code). Find the smallest
nwhere it differs and print it beside the truth.
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.
- Write
prefix_scores(words), returning(word, score)for each different word, alphabetically, and the oracleprefix_scores_scan. Trace["abc", "ab", "bc", "b", "ab"]. - Check every list in
BEDand 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. - 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).
- A student starts the sum at the root's count, which counts the empty prefix (B48 in the code). Find the smallest list in
BEDwhere it differs and print it beside the truth.
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.
- Write
merge_nodes,count_endsandmerge_tries. Merge["app", "apple", "ant"]with["apple", "apt", "bat"]and print the words and the size, beside the two sizes added. - Show why
bis unusable: delete a word ofbthataadopted and look ina, and insert intobbelow an adopted node. - Check every pair of lists from the first 241 of
BED(0 to 2 strings; by construction 241 * 241 = 58,081 pairs): the words ofaequal the union,len(a)equals its size, and the nodes equal the distinct prefixes of the union. - A student replaces a shared child with
b's (B49 in the code). Find the first pair inBEDorder where it loses a word and print it beside the union.
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.
- Write
suffix_trie(s)anddistinct_substrings(trie), and the oracledistinct_by_slices(a set of every slices[i:j]). Trace"banana". - Check every string over "a" and "b" of 0 to 6 letters (127 strings) against the oracle.
- For a random "acgt" string of 200 letters, one of 400,
"ab" * 200and"a" * 400, print the nodes, the boundn * (n + 1) / 2 + 1(assert the nodes stay within it), the distinct substrings, and the bytes and bytes per node fromtraced_bytes. Print what doublingndid to the nodes of the random strings, with the verdict built from the number. - 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.
- A student inserts only the proper suffixes (B50 in the code). Find the smallest string where it differs and print it beside the truth.
"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.
- 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 inBED. - 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. - 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 ratiotrie / setfor each. - 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.
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, socount_prefixis one walk of one dict lookup per character. The sorted list gets the count from twobisect_leftcalls (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 withstr.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 haskwords (k <= 0gives[]). 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.
- Write
bisect_countandbisect_complete, and check the trie, the set scan and the sorted list agree oncount_prefixand on the first 2 completions for every list inBEDwith every probe inPROBES. - 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. - Time the plain code, each the smallest of 3 runs, per query: counting with the trie, with
bisect_countand 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 withcompleteand withbisect_complete. Check that both give the same words. - Print a verdict only where it is earned: the scan against the trie when the ratio is at least 2; for the trie against
bisecton 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. Namesortedcontainers(not imported) as a sorted list that stays sorted as words arrive. Build every line from the variables.
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.
- For 10,000 and then 30,000 syllable words, time
Trie(words),set(words)andsorted(words), each the smallest of 3 runs. Print the total characters, the three times, the nanoseconds per character of the trie build, and the ratiostrie / setandtrie / sorted. - 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.
- Time one counting query per prefix two ways at 30,000 words:
CountTrie.count_prefixon 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 queriesqfor whichbuild + q * trie queryis underq * scan query(build the trie the queries run on, aCountTrie, and findqby 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 forq= 1, the break-even minus 1, the break-even and 1,000, with the cheaper one named from the totals. - 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).
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;
insertmay raise a weight but never lowers it. A word already stored with a weight at least as big changes nothing and returnsFalse; otherwise it returnsTrue; - 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.
- Trace it on 8 small weighted words, and raise one weight.
- 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 withwords_underand ranking them, and a plainsortedof 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. - 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. - For 300 prefixes of 1 to 3 letters, count the dict lookups of
topagainst the nodes a collect-and-rank query visits (the walk plus every node of the subtree), checking the answers are equal. - 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 wheretopdiffers from the truth, and print both.
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.
- Write
find_words_cuttingand 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, againstfind_words,board_wordsand oneboard_hasper word. - Print the calls of
find_words, of oneboard_hasper word, and ofevery_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. - 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_pathon the 6 x 6 board. Print a verdict only when the ratio is at least 2. - Run
find_words_cuttingon a fresh trie of the 10,000 words for each board and print the calls before (plainfind_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. - 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 inBEDorder) the smallest failing board and word list, and print the result beside the truth.
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, distinctly52L + 25of them for a word of L letters with no two equal neighbours), andnear_by_editskeeps 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.
- 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) thatnear_bruteagrees. 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). - 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.
- 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. - Time
near_bruteonce 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.
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 beforewalphabetically, whetherwis stored or not (so it equalsbisect_lefton the sorted list of the stored words). Walk downw: at each node add 1 if a word ends there (it is a proper prefix ofw), and add thewordsof every child whose letter is smaller thanw's next letter. Stop when the walk cannot followw.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 wheniis more than itswords.ioutside1..len(trie)raisesIndexError.
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.
- Write
rankandselect(with an optional counter of the child keys looked at) and trace them on["bat", "bath", "be", "a", "an", "and", "car"]. - Check every list in
BEDwith every probe:rankagainstbisect_leftonsorted(set(words)); everyselect(1..n)against the sorted list;selectof 0, -1 and n + 1 raisesIndexError(assert the type name); andselect(rank(w) + 1) == wfor 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. - 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. - A student's
rankalso countswitself when it is stored (count_self=True). Find by a scan ofBEDandPROBESin order the smallest list and probe where it differs frombisect_left, and print it beside the truth.
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.
- Check that
radix_searchandradix_starts_withagree with the trie on every list inBED(every list of 0 to 3 strings over "a" and "b", repeats and""included) with every probe inPROBES(the 40 strings of length 0 to 3 over "a", "b" and "c"). - 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 asetplus the words' own strings (sys.getsizeofeach). Print nodes, bytes per word and the radix/trie ratio. Note that labels of 2 or more letters are new strings built bycompress, so they are in the radix tree's bytes. - On each list check 10,000 probes (half stored, half with the last letter changed):
radix_searchequalsTrie.searchon 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. - 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.
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).
- Write the helpers, trace
[3, 10, 5, 25, 2, 8], and check that fewer than 2 numbers and a negative number raiseValueError(assert the type name) and that[5, 5]and[0, 0, 0]give 0. - Check 2,000 seeded lists of 2 to 8 numbers, each below
2^kfor a random k from 0 to 6, in random, ascending and descending order, againstmax_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. - For 1,500 random numbers below
2^30count 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) / 2and2 * 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. - 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.
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.
- Write
PrefixSuffixIndex(withf(prefix, suffix, lookups), wherelookupsis an optional one-item counter) and trace it on["apple", "ample", "maple", "apply", "apple"]; check that a word with#and a query with#raiseValueError(assert the type name). - Check every list in
BEDwith 64 pairs of short probes, and 300 seeded lists of up to 12 words of 0 to 6 letters over "a" and "b", againstscan_f. Count the cases among theBEDlists (empty list,"", a single word, a word that is a prefix of another, repeats, ascending and descending order), and assert each is above 0. - 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) / 2per word, aboutL^2 / 2. - On 500 queries count the dict lookups of
f(at mostlen(prefix) + len(suffix) + 1each) against the words the scan tests. - A student keeps the first index that reaches a node instead of the largest. Find by a scan of
BEDin order the smallest list and pair where it differs, and print it beside the truth.
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.
- Write
find_all(trie, text), and the oraclefind_all_scan(words, text)(trytext.startswith(w, i)for every word at every position). Check them on every list ofBEDagainst every text inSTRS(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. - Build 2,000 different syllable words and a text of exactly 12,000 letters made of stored words and single syllables, and check
find_allagainstfind_all_by_find(onestr.findloop per word) on the whole text, and against thestartswithoracle on its first 800 letters. - Count the trie's steps (moves from a node to a child, on a counted copy) against the start positions
str.findhas to consider (len(text) - len(w) + 1for each word), then timefind_allandfind_all_by_find, each the smallest of 3 runs, and print the ratio. - 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.
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.
- Write
near_prefix_nodes(trie, p, visits=None)(the nodes reached bypitself and by each string one edit fromp, keyed by that string;visits, if given, is a one-item list counting every move from a node to a child) andcomplete_typo(trie, p, visits=None)built on it withwords_under. Trace"cet"onWORDS. - Check against the oracle on the 241 lists of at most 2 strings of
BEDwith each of the 40PROBES, 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. - 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.
- 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.
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.
- 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 aCounter, 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. - 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.
- List the 10 most common words, ties broken by the word (alphabetical order).
Counter.most_commonbreaks ties by first appearance: show a small list where the two rules differ, and give the trie's top 10 with the explicit rule. - 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
Counterwithstartswith.
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.
- Write the class and trace three inserts, printing the edge dict and the end set.
- Check that
FlatTrieequalsTrie(the samesearchandstarts_withfor each of the 40PROBES, and the samelen) on every list ofBED. - 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.
- A student forgets to advance the next unused id (B64 in the code). Search for the smallest list and probe where it differs from
Trieand print both.
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.
- Write
count_under(p, n, steps=None)(how many of1..nstart with the digits ofp;steps, if given, is a one-item list that counts every range looked at) andkth_lex(n, k, steps=None). Start atcur = 1withk - 1numbers still to pass. While any remain: letc = count_under(cur, n). If the numbers still to pass are at leastc, skip the whole subtree (cur += 1, subtractc); otherwise step down to the first child (cur *= 10, subtract 1). RaiseValueErrorunless1 <= k <= n. - Check against the sorting oracle for every
kof everynfrom 1 to 300, and fornin 500, 999, 1000, 1001, 1999 and 2000, then for 30 seedednup to 2,000 with 20 seededkeach. Assert theValueErrors by type name. - For
n = 10^9count the steps over 2,000 seededkand for the lastk = n, assert the bound10 * d * dforddigits, and print the steps next to thek - 1numbers that listing them one by one would pass. - A student cuts each range at
ninstead ofn + 1(B65 in the code). Search for the smallestnandkwhere it differs and print both.
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".
- Write
trie_sort(words)(build aTrie, then list it withwords_under) and check that its output equalssorted(words)on both lists. Also check it on every list ofBEDwith the repeats removed. - Count, for each list: the characters
Nand the trie's nodesm, and the string comparisonssorted()makes (on a counted copy: astrsubclass whose__lt__counts). - Time build plus walk against
sorted(), and the walk alone (on an already built trie) againstsorted(), each the smallest of 3 runs, and print the ratios. - 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.
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.
- 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 addsSTRSin sorted order and one in reverse order and then removes them all: the trie, the list andScanWordsmust return the same value at every step, and the list must stay equal tosorted()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. - 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_leftcalls per count. - 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 / triefor each. Print no verdict from the clock: only the ratios. - 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.
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.
- Write
deepest_shared(trie)and the oracledeepest_shared_sorted(words). Check them on every list ofBED, and check the neighbour idea against every pair of words (itertools.combinations) on each of them. - 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. - 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. - 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.
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.
- Write
tokenise_longest(trie, text), and the oracletokenise_scan(words, text)that applies the same rule by trying every stored word at each position withtext.startswith(w, i)and keeping the longest. Check them on every list ofBEDwith every text ofSTRS(the 15 strings of 0 to 3 letters over "a" and "b"), and count the empty text, a result ofNone, 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. - Show the rule failing where another cut exists: the words
"ab","abc","cd"and the text"abcd". - 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. - 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.
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 andwords, 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 withp(a word equal topcounts,""counts all) and takes one walk oflen(p)dict lookups.complete(trie, p, k)returns the firstkstored words that start withp, alphabetically, and[]whenk <= 0or nothing starts withp.- A set (wrapped in
ScanWords, a Pythonsetwhose prefix questions scan every stored word withstr.startswith): membership isw in set, one hash and one lookup. The prefix count scans all the words; the firstkcompletions scan all the words, sort the matches and keepk; all the words in order issorted(set). - A sorted list made once with
sorted(words): membership is onebisect_leftand one equality test; the prefix count isbisect_left(lst, upper) - bisect_left(lst, p)withupper = p[:-1] + chr(ord(p[-1]) + 1), the string just above every word that starts withp(andlen(lst)forp == ""); the firstkcompletions arebisect_leftto the first word that is at leastpand then reading words while they start withp, up tok; 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.
- Check that the three structures answer alike, on the 241 lists of at most 2 strings of
BED(BEDholds every list of 0 to 3 strings, each 0 to 3 letters over "a" and "b",""included) with each of the 40PROBES(the strings of 0 to 3 letters over "a", "b", "c"), for membership, the prefix count and the completions withkof 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. - 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).
- 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).
- Print the table: a row for each cell with the three structures as columns, and under each timed row the steps behind it.
- 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.
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 withprefix, and a word equal toprefixcounts.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 ofsfrom the root. It returns the node reached, orNonewhere 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.
- Write four broken subclasses of
Trie, each a small change to the correct code:MarkEveryNodeTrie: itsinsertsetsendon every node it passes.MarkParentTrie: itsinsertkeeps aparentbesidenodeand marks the parent.IndexWalkTrie: its_walkusesnode.children[ch]instead ofget.ChildrenOnlyTrie: itsstarts_withasks only whether the node has children.
- 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 andlen()withScanWords. Then comparesearchandstarts_withon 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 correctTriemust fail none. - Show that
ChildrenOnlyTrieis not only wrong about"". Print its smallest failing list among the lists that do not hold"". Then insert"aa"into aMarkEveryNodeTrieand delete it. What doessearch("a")say now? - Fuzz the correct
Trieon 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. CatchExceptionas a failure, and assert that every count is above 0. - Build the closing line from the scan. Rebuild each class's smallest failing list and compare its
outlinewith the correctTrie'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.
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_markhas nousedgrid.find_no_lower_boundtestsnr < rows and nc < colswithout0 <=.find_stop_at_wordreturns as soon as the path spells a stored word.find_into_listcollects the words in a list.find_shared_rowsbuilds the grid as[[False] * cols] * rows.
- Write the five broken searches.
- 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 everythingboard_wordsfinds. Check thatfind_wordsmatches it on every board. - 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.
- Show what the shared rows do on the smallest board where
find_shared_rowsfails: mark cell (0, 0) in each grid and print both. This is DSA Topic 2's grid trap. - Fuzz
find_wordson 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. CatchExceptionas a failure.
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 withchildren[ch]instead ofget.
A check is good only if the bug can show on its input, and the first of these bugs hides from the usual check.
- Write the three classes, and a
run(cls, words, deletes)that inserts the words and then deletes the strings ofdeletesin order. After each delete, compare the return value,len(),searchon every word of the list, and the node count withScanWords. The right node count is the number of distinct prefixes of the stored words. Report the first disagreement, and treat an exception as one. - From every list of
BED, delete the 15STRSinSTRSorder:""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. - Now delete each list's distinct words in every order. Print the smallest list and order where
CutIgnoringEndsTrieloses a word. Show that the same list deleted shortest first passes. - Show what
NoEndCheckTriedoes tolen()on["ab"]when you delete"a"and then"ab". - 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?
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:
RootlessCountTrienever adds 1 to the root on insert.KeepZeroCountTrie'sdeletecounts 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.
- Write both classes. Write
lcp_oracle(words), the common prefix of the smallest and largest word, andrecount_ok(trie).recount_okrebuilds every count from theendflags with no recursion, and it finds no node with count 0 below the root. - On every list of
BED, insert the words, then delete them in the same order. After every step, comparelen(),count_prefixof every probe andlcpwithScanWords, then recount. Print each class's smallest failing list and what fails there. RootlessCountTrie's smallest failure holds"". Print its smallest failure without"", and say which probe is wrong.- Insert
"apple"into aKeepZeroCountTrieand delete it. Printlen(),count_prefix("a"),lcpandrecount_ok. - Fuzz the correct
CountTrieon 300 seeded scripts of 30 inserts and deletes over"ab"(in given, sorted or reverse-sorted order), withlcpchecked and every node recounted after each step. Count the cases.
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_kstops atlen(out) > k.complete_below_prefixstarts the stack with the prefix node's children.complete_no_guardleaves out thek <= 0test.
- Write the three broken versions.
- Check the correct
completeagainstScanWords.completeon every list ofBED, every probe, andk= None and -1 to 3. Then print each broken version's smallest failing list, prefix andk, beside the truth. complete_below_prefix's smallest failure is about"". Print its smallest failure on a list without"".- Sort the three into "returns too many" and "skips a word", using their outputs.
- Fuzz the correct
completeon 300 seeded lists over"abc"(in given, sorted or reverse-sorted order), with every probe andkfrom None and -1 to 5. Count the cases,k <= 0andkbelow the number of matches included.
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.
-
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 writeradix_lines(root), an alphabetical listing of the labels with no recursion. -
Trace the inserts
"team","tea","ten","to","toast","t", and print the splits and the tree after each one. -
For every list of
BED, insert in the list's order. Check each return value againstScanWords, every probe against the plainTrie, and the tree againstcompressof the finishedTrie, line for line and node for node. -
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. -
Write two broken lookups:
radix_search_first_charfinds the child by its first character and skips the label without comparing it.radix_starts_with_whole_edgesrequires every edge to fit inside the prefix.
Print each one's smallest failing list and probe, beside the truth.
-
Say in one line why delete is not built here.
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_swapswapsword[i]andword[i + 2].edits1_no_end_insertnever inserts after the last character.edits1_same_letterlets replace put back the same letter.one_edit_any_swapaccepts a swap of the first and last differing positions however far apart they are.
- Write the four broken versions.
- Take every pair of strings over
"abc"of length 0 to 4 (121 strings, 14,641 pairs, by construction), smallest first. Check a generator againstone_editand the test againstedits1. Print each one's smallest failing pair and how many pairs it gets wrong. - For
edits1_same_letter, check what its wrong pairs have in common. - Assert that
"aab"to"baa"is not one edit, and thatone_edit_any_swapaccepts it. - Fuzz the correct pair inside the spell-check:
near_by_edits(generate, then look up in a set) againstnear_brute(one_editon 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.
Nothing in Trie cares what a character is. A children dict takes any hashable key, and a word can be any sequence of them.
- 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. - 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. - Write
FoldOnInsertTrie, which folds case withstr.casefoldon insert only. Then writeFoldedTrie, which folds on insert, search,starts_withand delete. FindFoldOnInsertTrie'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 aScanWordsof folded words. Check thatFoldedTriehas none. - Build characters beyond ASCII with
chr()and print them withascii():- Store
"caf" + chr(233)and"stra" + chr(223) + "e", then search for the upper-case forms. - Compare
lower()andcasefold()onchr(223). - Print
chr(233) is chr(233)andchr(300) is chr(300), and say what CPython does with one-character strings.
- Store
- Fuzz
FoldedTrieon 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.
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.
- Store one word of 5,000 letters. Call
words_underand catch the error. Print only its type name, and whether the word is longer thansys.getrecursionlimit(). - Run
complete,count_nodesandoutlineon the same trie. They keep their own stack in a list.completemust return the word itself. compressrecurses 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 thatcompressfails on that chain whilecompletestill returns the first 3 words.- Fuzz
words_underandcompleteagainstsorted(set(words))on 300 seeded short lists (in given, sorted or reverse-sorted order). Count the cases.
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.
- Write
delete_prefix_live(the obvious version) and two fixes:delete_prefix_keys_firstloops overlist(node.children).delete_prefix_collect_firstcollects the words withcomplete, then deletes them.
- In one pass over every list of
BEDwith every prefix inSTRSplus"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. - Show that a
completeresult is a new list, so deleting afterwards does not change it, whilenode.childrenis the live dict. - Fuzz both fixes on 300 seeded lists over
"abc"(in given, sorted or reverse-sorted order) with a seeded prefix. Count the cases.
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).
- A string built at every node.
words_under_concat(node, prefix, out, built)hands each childprefix + ch, so every node builds a new string as long as its depth.words_underkeeps 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 tobuilt[0], and check they return the same words aswords_under. First, for a trie holding one word of L letters with L = 50, 100 and 200, the strings built areL * (L + 1) / 2the first way andLthe 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. - 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 keepsk.completestops when it hask. Writecompleteas a counted copy too (visits[0]counts nodes taken off the stack) and check it returns whatcompletereturns. On a trie of 10,000 syllable words withk = 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 withcount_nodes) and thatcompletevisits at most1 +the letters, beyond the prefix, of the words it returns. - 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 ofboard_hason both words for L = 50, 100 and 200: they areL * L(predicted by formula; assert 2,500, 10,000 and 40,000), while the words"a" * kwithk <= Lare found after exactlykcalls.board_has_guardedfirst counts letters (aCounter, 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 withboard_hason every word"a" * kfor 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.
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:
sys.getsizeof(trie)on an empty trie and on the full one. Print both.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.getsizeofof each, summed).traced_bytesaround 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 besidesys.getsizeofof the word list plus the 10,000 strings.- Walk every node and add
sys.getsizeof(node)alone, then addsys.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.
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.
- Write
max_xor_bitswith a smallBitNode(a two-slot listkids). The walk builds the xor bit by bit: at bitbit adds1 << bwhen the opposite child exists and goes there, and otherwise takes the same-bit child. - Write two broken functions:
max_xor_narrow, which fixes the width atB = 3"because the test numbers were small", andmax_xor_low_first, which stores and walks the bits low bit first. - 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 raiseValueError(by type name) in all three, and thatmax_xor_bitsis right on the rest. - 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.
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):insertsets 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):insertadds 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").
- 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 comparescount_prefixof 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). - 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.
- 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.
- 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.
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) andcount_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 firstkstored words that start with the prefix, alphabetically, all of them whenkis None,[]whenk <= 0or 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).
- Write
check_trie(make, complete_fn=complete, stop_at_first=False), wheremake()returns a new empty trie. For every list ofBEDit inserts the words in order and compares each return value with the oracle, compareslen, then comparessearch,starts_withandcount_prefix(where present)complete_fn(trie, probe, 2)andcomplete_fn(trie, probe)(k None) for every probe ofPROBES, then deletes all 15 strings ofSTRSin order, comparing each return value,len, andsearchafterwards. 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. - Run it on
Trieand onCountTrie: assert zero failures and that every case count is above 0, and print the counts. - Plant six bugs and run the suite on each with
stop_at_first=True, printing the first failure of each: aTriewhosedeleteleaveslenunchanged; one whosedeletereturns True for an absent word; one whoseinsertreturns True for a duplicate;completethat returns[]whenkis None (a differentcomplete_fn); aCountTriewhosecount_prefixleaves out the word equal to the prefix; and aTriewhosedelete("")refuses. Assert that every one is caught and say which list, inBEDorder, first exposes each.
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 withset_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 mostkof them:[]whenk <= 0or no word starts with the prefix.suggest_as_typed(text, k)is a list with one entry for each letter typed: entryi(from 1) istop(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).
- Write the service and
ScanService, a dict of word to weight with every question answered by scanning all the words (the oracle). - 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(withkfrom -1 to 4) andsuggest_as_typedon two random probes. Count the cases reached (add new and duplicate, remove present and absent,set_weightpresent and absent, atopwhose answer holds two equal weights,""stored,k <= 0), assert each is above 0, and count any exception as a failure. - 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 plaincountandtop(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. - 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". Fortopprint 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.
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 usedw; 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).
- Make a dictionary of 1,500 syllable words with a seeded
random.Random, and a corpus of 20,000 tokens drawn from it with weights1 / (rank + 1)(so a few words are common and most are rare);countsis aCounterof the corpus. - Write
correct, andcorrect_brute(same contract, built onnear_bruteand a set, never a trie). - 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
correctagainstcorrect_bruteon all 500, and check thatnear_by_trie,near_by_edits(alphabet a to z) andnear_bruteagree on every query. Count what each answer was (the word itself, one or more candidates, nothing) and assert each is above 0. - Count the trie's steps per query (on a counted call) against the number of candidates
edits1generates 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).
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).
- 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).
- Check
find_boggleagainst oneboggle_hassearch 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 againstboggle_words_permon 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. - 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. - Say from the counts how much work the trie saves on a board, and how the saving compares with trying every path.
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
shownis[]. - Exactly one match: the partial word becomes the match followed by one space, and
shownis[]. - Several matches: the partial word becomes the longest common prefix of the matches (no space), and
shownis 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).
- Write
CommandNode(achildrendict from a word to a node, andend),CommandTrie(commands)(each command split on spaces),tab, andtab_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. - Use 36 hand-written commands over
git,cargoand a few single words (ls,less,list,cd,cat,cp). Checktabagainsttab_scanon 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. - Show one line of each kind with its result, and one short typing session where each Tab is followed by the next typed letters.
- 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.
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).
- Write
TopNodeandTopTrie(words_with_weights)with the cached best 3,SearchBox(type(ch)andbackspace()both return the 3 suggestions;lookups, if given, is a one-item list that counts every child lookup) andsuggest_from_root(trie, text, lookups), the way that walks the whole text from the root again after every keystroke. - 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).
- On a dictionary of 800 syllable words with weights from 1 to 20 (ties happen), check both ways against a scan (
sortedover(-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. - 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.
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).
- Write
rack_wordsand a scan to check it:rack_scan(words, rack)tests each distinct word with aCounter, 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 theValueErrors, then play four racks againstWORDS. - Check
rack_wordsagainstrack_scanon every list inBEDwith 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. - 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. - 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.
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.
- Write
PhraseTrie(add(phrase)returns whether the phrase was new;""and all-space phrases are ignored and return False) andhighlight(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. - 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 inBEDused 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. - 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.
- 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.
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.
- Write
pack(root)andload(text), both iterative.loadraisesValueErroron anythingpackcould not have written from a tree made bycompress: 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 (compresswould 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 (ValueErrorotherwise). Trace the pack of a small list. - Round trip on every list in
BED:load(pack(compress(trie)))holds exactly the distinct words (listed by a walk), answersradix_searchandradix_starts_withlike the trie on every probe inPROBES, and packs to the same string again. - 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,aandb. Check every damaged string either raisesValueErroror 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 otherExceptionas a failure. - 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.
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.
- Write
parse_route(text)andparse_address(text)withstr.split(ValueErrorunless 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 classRouteTablewithadd_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) andlookup(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. - Write
lookup_scan(routes, address), which tests every route with a shift and keeps the longest match. Checklookupagainst 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. - Print the bits walked per lookup (average and largest, never above 32) against the routes the scan tests.
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.
- Write
PathIndexwithadd(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) anddeepest(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. - 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 adeepestthat stops partway. - On 10,000 seeded paths of 2 to 6 names, count the dict lookups of
count_filesandlistingper query against the tuples the scan reads.
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.
- The tree of prefixes. Store "car", "card", "care", "cat" and "do"; print
outlineof the trie, and check that the nodes are exactly the distinct prefixes of the words,""(the root) included. - The end flag. Show that "ca" is a path but not a word (
searchFalse,starts_withTrue) 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. - One insert, traced. Insert "cart" with a traced copy of
insertthat 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. - 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).
- 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'scompleteon 1,000 prefixes; a verdict only at a ratio of 2 or more). Close with the one-line summary, built from the numbers.
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
_walkwritten withnode = 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_withsaid True for, in a set, and answers from that set next time;deletedoes not clear it. - D4
compressthat also folds the root into its only child when the root ends no word, so the root gets a non-empty label. - D5
one_editthat 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.
- Write each prediction with its reason before the scans run (as data in the program, printed first).
- 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.
"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.
- Build all three from 10,000 syllable words and measure their bytes per word, structure only (the strings built first), with
traced_bytes. - For each operation, check the candidate ways agree, then count their work and time them: membership (set
inagainst triesearch), prefix counts (twobisect_leftcalls, counting string comparisons in a counted copy, against the trie's lookups), the first 5 words (a slice of the sorted list againstcomplete), 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. - 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).
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.
- 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.
- 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 reversedwords[j]beforewords[i]runs out, the pair works when the rest ofwords[i]is a palindrome; whenwords[i]runs out at a node, every word noted there pairs with it. Test the rest ofwords[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). - Check the two on every list in
BEDand 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. - 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.
"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 whenwis stored.count_prefix(p): how many stored words start withp(a word equal topcounts;""counts every word; 0 on an empty dictionary).top(p, k): thekstored words starting withpthat have the highest weight, highest first, ties broken by the word alphabetically; fewer if fewer match;[]whenk <= 0or nothing matches.suggest(w): the stored words exactly one edit fromw, sorted. One edit is: delete one letter, insert one letter, replace one letter by a different one, or swap two adjacent different letters.witself 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).
- 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. - Validate every request on the 10,000-word service against its check:
containsandcount_prefixagainstScanWords(2,000 words, half stored; 300 prefixes of 0 to 4 letters),topagainst sorting every match by (weight descending, word) for k = 0, 1, 5 and 50,suggestagainstnear_bruteon 40 misspelled words,on_boardon a 5 x 5 board againstboard_hasrun for every stored word, and on 10 boards of 3 x 3 againstboard_words(paths of up to 5 letters, so the words of up to 5 letters). - Report the memory: bytes per word for the trie and the weights, against a set and a sorted list of the same words.
- Do the same requests with a set and with a sorted list (two
bisect_leftcalls for a prefix's range, as in DSA Topic 3): membership with a set; counting by twobisect_leftcalls and by a set scan;topfrom the sorted range;suggestby generating every one-edit string and probing the set;on_boardby searching for each word separately. Count the work where it can be counted (dict lookups against string comparisons; fortop, 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 withbisect, fortopand forsuggest, 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. - 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.