Courses / DSA Patterns for Working Engineers / Chapter 23
Module 7 · Trees and tries · Chapter 23 of 39
Tries: Prefix Trees for Search and Autocomplete
Builds on Tree Depth-First Search: Recursion That Returns Answers Upward. Next up: Hash Maps: Lookups, Complements and Pattern Matching.
Part 1 · Introduction to tries
Words as paths
A search box suggests product names after two letters, and a phone keyboard completes words as you type. Both need to answer questions about the beginnings of words, and a plain list of words answers those slowly.
A trie, also called a prefix tree, stores a set of words as paths in a tree. The root stands for the empty string. Each edge carries one character, and each node stands for the string of characters on the path from the root to it. Words that begin the same way share the beginning of their path, so steel and steep share the nodes for s, t, e and e, and then split.
Each node needs two things: a map from a character to the child node it leads to, and a flag saying whether a stored word ends here. The flag is needed because a stored word can be a prefix of another. If tea and team are both stored, the node for tea is on the way to team, and only the flag tells you that tea is a word in its own right.
Code blocks follow the convention set out in the first chapter.
export class TrieNode { children: Map<string, TrieNode> end: boolean // a stored word finishes at this node constructor() { this.children = new Map() this.end = false } }
trie.ts: a node, with a Map of children and an end flag
Insert, search and prefix
Every operation follows the letters of its argument down from the root. Insert creates the nodes that are missing and sets the end flag on the last one. Search follows the letters and answers yes only if the walk does not fall off and the node reached has its end flag. Prefix check is the same walk, answering yes as long as the walk does not fall off and some word passes through the node reached.
The loop reads a string with for (const ch of word), which steps through code points. A character outside the basic range, such as an emoji, is one step and not two, as the test below shows. Reading with an index would split it.
export class Trie { root: TrieNode count: number // how many distinct words are stored constructor() { this.root = new TrieNode() this.count = 0 } insert(word: string): void { let node = this.root for (const ch of word) { let next = node.children.get(ch) if (next === undefined) { next = new TrieNode() node.children.set(ch, next) } node = next } if (!node.end) { node.end = true this.count++ } }
trie.ts: the class, and insert
// The node reached by following the letters of `text`, or null. find(text: string): TrieNode | null { let node = this.root for (const ch of text) { const next = node.children.get(ch) if (next === undefined) return null node = next } return node } has(word: string): boolean { const node = this.find(word) return node !== null && node.end } // True when some stored word begins with `prefix`. startsWith(prefix: string): boolean { const node = this.find(prefix) return node !== null && (node.end || node.children.size > 0) } }
trie.ts, continued: find, has and startsWith
The cost of each operation depends on the length of the word and not on how many words are stored. It takes one map lookup per letter, so the time is proportional to the length of the word. A list of a lakh words checked one by one would take a lakh comparisons for the same question.
The empty string deserves attention. An empty trie stores no words, so startsWith("") is false there: no stored word begins with anything. Once the empty string is inserted, or any other word, the root has the end flag or children, and the answer becomes true.
Checking it, and what it costs in memory
The tests count the nodes of a trie, root included, with a small helper that walks it with a stack.
// Number of nodes, root included. export function countNodes(trie: Trie): number { let total = 0 const stack: TrieNode[] = [trie.root] while (stack.length > 0) { const node = stack.pop()! total++ for (const child of node.children.values()) stack.push(child) } return total }
trie.ts: the number of nodes in a trie
test('an empty trie', () => { const t = new Trie() assert.equal(t.has(''), false) assert.equal(t.startsWith(''), false) assert.equal(t.has('a'), false) assert.equal(countNodes(t), 1) }) test('the empty word, repeats, and prefixes of words', () => { const t = new Trie() t.insert('') assert.equal(t.has(''), true) assert.equal(t.startsWith(''), true) t.insert('steel') t.insert('steel') t.insert('steep') assert.equal(t.count, 3) assert.equal(t.has('stee'), false) // a prefix, not a stored word assert.equal(t.startsWith('stee'), true) assert.equal(t.has('steels'), false) assert.equal(t.startsWith('steels'), false) })
trie.test.ts: edge cases
test('letters are code points, so an emoji is one step', () => { const t = new Trie() t.insert('tea🍵') assert.equal(t.has('tea🍵'), true) assert.equal(t.startsWith('tea'), true) assert.equal(countNodes(t), 5) }) test('agrees with a Set and a scan on 2,000 random lists', () => { const rand = mulberry32(91) const word = () => Array.from({ length: Math.floor(rand() * 5) }, () => 'ab'[Math.floor(rand() * 2)]).join('') for (let round = 0; round < 2000; round++) { const words = Array.from({ length: Math.floor(rand() * 8) }, word) const t = new Trie() words.forEach((w) => t.insert(w)) const set = new Set(words) assert.equal(t.count, set.size) for (let k = 0; k < 6; k++) { const q = word() assert.equal(t.has(q), set.has(q)) assert.equal(t.startsWith(q), words.some((w) => w.startsWith(q))) } } })
trie.test.ts, continued: code points and a comparison with a Set
✔ an empty trie (0.6108ms) ✔ the empty word, repeats, and prefixes of words (0.1661ms) ✔ letters are code points, so an emoji is one step (0.1113ms) ✔ agrees with a Set and a scan on 2,000 random lists (17.5132ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output of one run; the millisecond figures vary
The last test inserts random words over two letters into a trie and a Set, with empty words and repeats included, and compares has, startsWith and the count against a Set and a scan with startsWith.
Part 2 · A prefix index for product search
The problem
A shop wants a search box that answers two questions about its product names: is this exactly a product, and does any product begin with what the shopper has typed so far? Names are strings with letters and spaces.
The two questions are the two methods of the trie from the previous lesson. has asks about an exact name and needs the end flag. startsWith asks about a beginning and needs only that the walk succeeds. That is the whole index: insert every name once, and answer each query by walking.
// Product names for a shop search box. const names = [ 'steel bottle', 'steel bowl', 'steel plate', 'cotton towel', 'cotton sheet', 'copper pot', 'copper bowl', ] const index = new Trie() for (const name of names) index.insert(name) for (const q of ['steel bowl', 'steel', 'cotton', 'copper pan', '']) { const exact = index.has(q) const prefix = index.startsWith(q) const shown = JSON.stringify(q).padEnd(14) console.log(shown, 'exact', exact, 'prefix', prefix) }
Seven names, and five queries
"steel bowl" exact true prefix true "steel" exact false prefix true "cotton" exact false prefix true "copper pan" exact false prefix false "" exact false prefix true
Output of one run
The first query is exactly a name. The second, steel, is a beginning of three names but not a name by itself, so it is a prefix and not a match. The third is also only a prefix. copper pan shares the beginning copper p with copper pot, but no name starts with the whole of it, so the answer is false for both. The empty string is a prefix of every name, so it is true here.
Sharing a path
When a name is inserted, the letters that already exist are followed, and nodes are created only from the first letter that is missing. Inserting steel plate after steel bottle and steel bowl creates nodes only for plate, because the path for steel is already there. This is why inserting a name costs time proportional to its length and no more.
Watch for the new word tab following letters that already exist
Read it as steps
only the last letter of the new word needs a node
The scene shows four stored words and a fifth, tab. Its first two letters follow the nodes that tap and tape already made, and only the b is new. The label end marks nodes where a stored word finishes.
A repeated name changes nothing: inserting it again follows the existing path and finds the end flag already set. The trie keeps a count of distinct words, which counts it once. A name that is a prefix of an existing name, such as steel after steel bowl, creates no node at all and only sets the end flag on a node that is already there.
Comparing with a Set and a scan
The shop index is checked in two ways. First, every name and every beginning of every name must answer correctly, and a name with a letter added must not be a prefix of anything. Second, random shops are built from six words, one or two words to a name, and compared with a Set for exact queries and with a scan using startsWith for prefix queries. That runs 2,000 rounds with eight queries each, and each query is a random cut-off of a random name, so many end in the middle of a word.
const shop = [ 'steel bottle', 'steel bowl', 'steel plate', 'cotton towel', 'cotton sheet', 'copper pot', 'copper bowl', ] test('every name, and every beginning of every name', () => { const index = new Trie() shop.forEach((n) => index.insert(n)) for (const name of shop) { for (let k = 0; k <= name.length; k++) { const head = name.slice(0, k) assert.equal(index.startsWith(head), true) assert.equal(index.has(head), shop.includes(head)) } assert.equal(index.startsWith(name + 'x'), false) } })
product.test.ts: every name and every beginning
test('random shops built from a small vocabulary', () => { const rand = mulberry32(96) const words = ['steel', 'cotton', 'copper', 'bottle', 'bowl', 'pot'] const pick = () => words[Math.floor(rand() * words.length)] const name = () => Array.from({ length: 1 + Math.floor(rand() * 2) }, pick).join(' ') for (let round = 0; round < 2000; round++) { const names = Array.from({ length: Math.floor(rand() * 8) }, name) const index = new Trie() names.forEach((n) => index.insert(n)) for (let k = 0; k < 8; k++) { const q = name().slice(0, Math.floor(rand() * 14)) assert.equal(index.has(q), names.includes(q)) const some = names.some((n) => n.startsWith(q)) assert.equal(index.startsWith(q), some) } } })
product.test.ts, continued: random shops
✔ every name, and every beginning of every name (0.9174ms) ✔ random shops built from a small vocabulary (20.8868ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
The cases that tend to go wrong are all in the tests: the empty string, a repeated insert, a stored word that is a prefix of another (stee is a prefix of steel but not a word), a query longer than any stored word, and a character outside the basic range. Related on LeetCode: Implement Trie (Prefix Tree).
In the demo, why does steel answer true for prefix but false for exact?
Part 3 · Three suggestions while typing
The problem
As a shopper types, the box shows up to three product names that begin with the letters so far, the three smallest in alphabetical order. After s it shows three names, after st perhaps the same three, and after steel b only the ones that fit. Names are non-empty and use plain letters and spaces.
A trie can answer this in two ways. The first walks the subtree below the prefix in alphabetical order and stops after three words. It needs no extra storage, but each query may visit many nodes, and it must sort the children at each node it enters. The second keeps the answer on the nodes: every node stores the three smallest names that pass through it. A query then walks down the prefix and reads the list, with nothing more to do.
The cost moves to insertion. Each inserted name is offered to every node on its path, including the root. A node keeps a sorted list of at most three names, adding the new one only if it is not already there, then dropping the largest if the list has grown to four. The default sort() compares strings by UTF-16 code units, which is the same order the comparison < uses, so the lists agree with the sorted-array method below.
const K = 3 // Keeps the three smallest names (by code unit order) in `top`. function offer(top: string[], name: string): void { if (top.includes(name)) return top.push(name) top.sort() if (top.length > K) top.pop() }
suggest.ts: keeping the three smallest names of a list
class SNode { children: Map<string, SNode> top: string[] // the smallest names that pass through this node constructor() { this.children = new Map() this.top = [] } }
suggest.ts, continued: a node that holds its suggestions
// Names are non-empty and use plain ASCII letters and spaces. export class SuggestTrie { root: SNode constructor() { this.root = new SNode() } insert(name: string): void { if (name === '') throw new RangeError('empty name') let node = this.root offer(node.top, name) for (const ch of name) { let next = node.children.get(ch) if (next === undefined) { next = new SNode() node.children.set(ch, next) } node = next offer(node.top, name) } }
suggest.ts, continued: the trie and insert
// Up to three names that start with `prefix`, smallest first. suggest(prefix: string): string[] { let node = this.root for (const ch of prefix) { const next = node.children.get(ch) if (next === undefined) return [] node = next } return [...node.top] } }
suggest.ts, continued: suggest
Typing
While the shopper types, ask for the suggestions after each letter. The prefix grows by one letter at a time, so a loop builds it up and queries each one.
// The suggestions after each letter of what the shopper has typed. export function whileTyping( trie: SuggestTrie, typed: string, ): string[][] { const out: string[][] = [] let prefix = '' for (const ch of typed) { prefix += ch out.push(trie.suggest(prefix)) } return out }
suggest.ts: the suggestions after every letter
const trie = new SuggestTrie() const names = [ 'steel bowl', 'steel bottle', 'steel plate', 'steam iron', 'stand fan', 'cotton towel', 'steel spoon', ] for (const n of names) trie.insert(n) whileTyping(trie, 'steel b').forEach((s, i) => { console.log(JSON.stringify('steel b'.slice(0, i + 1)).padEnd(10), s) })
Seven names, and the suggestions for steel b
"s" [ 'stand fan', 'steam iron', 'steel bottle' ] "st" [ 'stand fan', 'steam iron', 'steel bottle' ] "ste" [ 'steam iron', 'steel bottle', 'steel bowl' ] "stee" [ 'steel bottle', 'steel bowl', 'steel plate' ] "steel" [ 'steel bottle', 'steel bowl', 'steel plate' ] "steel " [ 'steel bottle', 'steel bowl', 'steel plate' ] "steel b" [ 'steel bottle', 'steel bowl' ]
Output of one run
After s the three smallest names are stand fan, steam iron and steel bottle. Typing the third letter, e, removes stand fan, and the list shifts to include steel bowl. By stee the list is all steel names, and a trailing space changes nothing because every remaining name has one. After steel b only two names fit, so only two are shown.
Query cost is proportional to the length of the prefix, not to the number of names. Insertion costs more than before: each of a name's letters offers the name to a node, and each offer may sort a list of at most four, so the time is proportional to the length of the name times a small constant.
Against sort and binary search
A simpler design needs no trie at all. Sort the names once. For a prefix, binary search for the first name that is not smaller than the prefix, then read forward while names still begin with it, up to three. All names with the prefix sit next to each other in sorted order, which is why this works.
// The same answer from a sorted array: find the first name that is not // smaller than the prefix, then read on while the prefix still matches. export function suggestSorted( sorted: string[], prefix: string, ): string[] { let lo = 0 let hi = sorted.length while (lo < hi) { const mid = (lo + hi) >> 1 if (sorted[mid] < prefix) lo = mid + 1 else hi = mid } const out: string[] = [] for (let i = lo; i < sorted.length && out.length < K; i++) { if (!sorted[i].startsWith(prefix)) break out.push(sorted[i]) } return out }
suggest.ts: binary search in a sorted array
The two designs give the same answers, and the test checks it on 2,000 random lists. Choosing between them is a matter of how the data changes. The sorted array is smaller and simpler, but adding a name means inserting into the array. The trie takes new names in one pass of their length. The trie is also the better base when more features are needed, such as the wildcard search in a later lesson.
test('edge cases', () => { const t = new SuggestTrie() assert.deepEqual(t.suggest('a'), []) assert.deepEqual(suggestSorted([], 'a'), []) assert.throws(() => t.insert(''), RangeError) t.insert('pan') t.insert('pan') // a repeated name is kept once assert.deepEqual(t.suggest('p'), ['pan']) assert.deepEqual(t.suggest('pans'), []) assert.deepEqual(whileTyping(t, 'pax'), [['pan'], ['pan'], []]) }) test('the trie matches sorting and binary search', () => { const rand = mulberry32(92) const name = () => Array.from({ length: 1 + Math.floor(rand() * 5) }, () => 'abc '[Math.floor(rand() * 4)]).join('') for (let round = 0; round < 2000; round++) { const names = Array.from({ length: Math.floor(rand() * 12) }, name) const trie = new SuggestTrie() names.forEach((n) => trie.insert(n)) const sorted = [...new Set(names)].sort() for (let k = 0; k < 6; k++) { const prefix = name() const want = suggestSorted(sorted, prefix) assert.deepEqual(trie.suggest(prefix), want) } } })
suggest.test.ts
✔ edge cases (1.3922ms) ✔ the trie matches sorting and binary search (29.5067ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
The edge cases are an empty list, an empty name (rejected), a repeated name, which is kept once, and a prefix that matches nothing. Related on LeetCode: Search Suggestions System.
Part 4 · Replacing words with their roots
The problem
A support team groups customer messages by topic. It has a list of roots, such as pay and ship. In a sentence, every word that starts with a root should be replaced by that root, and if more than one root fits, the shortest one wins. Words with no root stay as they are.
Put the roots in a trie. For each word of the sentence, walk down the trie with its letters. The walk can end three ways. If it reaches a node with the end flag, a root has been found, and because the walk goes from short to long, the first such node is the shortest root. If the walk falls off the trie, no root fits and the word stays. If the word ends first, the word is shorter than any root that fits and also stays.
// Replaces each word of a sentence by its shortest root, if it has one. export function replaceWords( roots: string[], sentence: string, ): string { const trie = new Trie() for (const r of roots) if (r !== '') trie.insert(r) return sentence .split(' ') .map((word) => { let node = trie.root let prefix = '' for (const ch of word) { const next = node.children.get(ch) if (next === undefined) break prefix += ch node = next if (node.end) return prefix // the shortest root ends first } return word }) .join(' ') }
roots.ts: the shortest root, or the word itself
Splitting the sentence on a single space and joining with a single space keeps the original spacing, including doubled spaces, because the empty pieces between them pass through unchanged. An empty root would match everything, so it is ignored.
A common prefix by a trie
A related question: what is the longest beginning that every word in a list shares? Insert all the words. Then the shared beginning is the path from the root that does not branch and does not pass a word end. Follow it while the node has exactly one child and no word has ended there, collecting letters.
// The longest prefix shared by every word, read off a trie: follow the // path while it does not branch and no word has ended. export function commonPrefix(words: string[]): string { if (words.length === 0) return '' const trie = new Trie() for (const w of words) trie.insert(w) let node = trie.root let out = '' while (node.children.size === 1 && !node.end) { const [[ch, next]] = node.children out += ch node = next } return out }
roots.ts: follow the path until it branches or a word ends
The condition !node.end matters. For car, card and care, the path c, a, r ends at a node where a word ends, so the walk stops there even though the node has two children for other reasons. And for a list that contains the empty string, the root itself has the flag, so the answer is empty.
const roots = ['pay', 'ship', 'ref', 'order'] console.log(replaceWords(roots, 'payment shipped refunded orders late')) const ids = ['invoice-104', 'invoice-1042', 'invoice-10'] console.log(JSON.stringify(commonPrefix(ids))) console.log(JSON.stringify(commonPrefix(['north', 'south'])))
Roots in a sentence, and the common prefix of invoice numbers
pay ship ref order late "invoice-10" ""
Output of one run
Matching is by exact letters, so Pay would not match the root pay. If the input has mixed case, change both sides to one case first.
The sentence comes out as pay ship ref order late: four words replaced by their roots and late untouched. The three invoice numbers share invoice-10, because one of them stops there. north and south share nothing, so the answer is an empty string.
Checking both
For the common prefix the check is a letter-by-letter scan: start with the first word as the candidate and cut it down against every other word. That shares no code with the trie. The tests use short words over two letters, so most lists share some prefix and many are empty or contain repeats.
// Compare the first word with each of the others, letter by letter. function scan(words: string[]): string { if (words.length === 0) return '' let prefix = words[0] for (const w of words) { let i = 0 while (i < prefix.length && i < w.length && prefix[i] === w[i]) i++ prefix = prefix.slice(0, i) } return prefix }
roots.test.ts: a letter-by-letter scan
test('roots: a shorter root wins, and spaces survive', () => { assert.equal(replaceWords(['pa', 'pat'], 'the patch'), 'the pa') assert.equal(replaceWords([], 'no roots here'), 'no roots here') assert.equal(replaceWords(['a'], ''), '') assert.equal(replaceWords(['a'], 'ab ac'), 'a a') // An empty root is ignored. assert.equal(replaceWords([''], 'ab'), 'ab') }) test('common prefix: empty list, one word, an empty word', () => { assert.equal(commonPrefix([]), '') assert.equal(commonPrefix(['cable']), 'cable') assert.equal(commonPrefix(['cable', '']), '') assert.equal(commonPrefix(['car', 'car', 'car']), 'car') assert.equal(commonPrefix(['car', 'card', 'care']), 'car') }) test('common prefix agrees with a letter-by-letter scan', () => { const rand = mulberry32(93) const word = () => Array.from({ length: Math.floor(rand() * 6) }, () => 'ab'[Math.floor(rand() * 2)]).join('') for (let round = 0; round < 3000; round++) { const words = Array.from({ length: Math.floor(rand() * 6) }, word) assert.equal(commonPrefix(words), scan(words)) } })
roots.test.ts, continued: the tests
✔ roots: a shorter root wins, and spaces survive (0.6953ms) ✔ common prefix: empty list, one word, an empty word (0.1727ms) ✔ common prefix agrees with a letter-by-letter scan (11.5916ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run; the millisecond figures vary
A trie is not the cheapest way to find a common prefix, because the scan needs no extra memory. The trie version shows how its structure answers the question directly: a branch point is exactly where the common prefix ends. Related on LeetCode: Replace Words, Longest Common Prefix.
Why is the first root found on the walk the shortest one?
Part 5 · A dictionary with wildcards
The problem
A word game stores a dictionary and checks patterns in which a dot stands for any one letter. The pattern c.t matches cat and cot, and the pattern ... matches any three-letter word. A pattern must match a whole word, so c. does not match cot. Words and patterns use the letters a to z.
A letter in the pattern means follow one child, as before. A dot means try every child, because any of them might lead to a match. That makes the search recursive: at a dot, call the search on each child in turn with the rest of the pattern, and stop with yes at the first that succeeds. If every child fails, the answer for this node is no.
// A word list where a search pattern may use '.' for any one letter. // Words and patterns use the letters a to z only. export class WordDictionary { trie: Trie visits: number // nodes entered by searches, for measuring constructor() { this.trie = new Trie() this.visits = 0 } add(word: string): void { if (!/^[a-z]*$/.test(word)) throw new RangeError('letters a-z only') this.trie.insert(word) }
wild.ts: the dictionary and its add method
search(pattern: string): boolean {
if (!/^[a-z.]*$/.test(pattern)) {
throw new RangeError('a-z and . only')
}
const go = (node: TrieNode, i: number): boolean => {
this.visits++
if (i === pattern.length) return node.end
if (pattern[i] === '.') {
for (const child of node.children.values()) {
if (go(child, i + 1)) return true
}
return false
}
const next = node.children.get(pattern[i])
return next !== undefined && go(next, i + 1)
}
return go(this.trie.root, 0)
}
}wild.ts, continued: a search that branches at dots
Why not expand the dots into letters and look each version up? A pattern with d dots over 26 letters has up to 26 to the power d versions, which is far worse than one walk of the trie.
The counter visits records how many nodes a search enters, so that cost can be measured and not guessed.
How much work a dot costs
It looks as if many dots could make the search explode, since each dot multiplies the branches. But a node in a trie can be reached by only one path, and the search enters it at the pattern position equal to its depth. So a search can never enter the same node twice, and the work is at most the number of nodes in the trie, however many dots there are.
const rand = mulberry32(8) const d = new WordDictionary() // 800 random five-letter codes over the letters a to e. const letter = () => 'abcde'[Math.floor(rand() * 5)] for (let i = 0; i < 800; i++) { d.add(Array.from({ length: 5 }, letter).join('')) } console.log('words:', d.trie.count, 'trie nodes:', countNodes(d.trie)) const queries = ['abcde', 'a.c.e', '.....', '....', '......', 'eeeee.'] for (const q of queries) { d.visits = 0 const found = d.search(q) const shown = q.padEnd(7) + String(found).padEnd(6) console.log(shown, 'nodes entered', d.visits) }
800 random five-letter codes and six patterns
words: 698 trie nodes: 1299 abcde true nodes entered 6 a.c.e true nodes entered 8 ..... true nodes entered 6 .... false nodes entered 601 ...... false nodes entered 1299 eeeee. false nodes entered 6
Output of one run
Watch for the dot trying every child, and one branch dying
Read it as steps
the co branch fails, the ca branch reaches car
In the scene the pattern c.r reaches its dot after the letter c. The branch through co has no r, so it fails, and the branch through ca reaches car, so the search answers yes.
Checking against a regular expression
A dot in a regular expression also matches any single character, so a pattern like c.t can be tested directly with new RegExp("^c.t$"). The check turns each random pattern into an anchored regular expression and tests every stored word. The words are over the letters a, b and c, and the patterns also use the dot, so the regular expression is safe to build.
test('edge cases', () => { const d = new WordDictionary() assert.equal(d.search(''), false) assert.equal(d.search('.'), false) d.add('') assert.equal(d.search(''), true) assert.equal(d.search('.'), false) d.add('cot') assert.equal(d.search('c.t'), true) assert.equal(d.search('c.'), false) // the whole word must match assert.equal(d.search('c.t.'), false) assert.equal(d.search('...'), true) assert.throws(() => d.add('Cot'), RangeError) assert.throws(() => d.search('c*t'), RangeError) })
wild.test.ts: edge cases
test('agrees with a regular expression on 3,000 random lists', () => { const rand = mulberry32(94) const make = (alphabet: string) => () => Array.from({ length: Math.floor(rand() * 5) }, () => alphabet[Math.floor(rand() * alphabet.length)]).join('') const word = make('abc') const pattern = make('abc.') for (let round = 0; round < 3000; round++) { const words = Array.from({ length: Math.floor(rand() * 8) }, word) const d = new WordDictionary() words.forEach((w) => d.add(w)) for (let k = 0; k < 6; k++) { const p = pattern() const re = new RegExp('^' + p + '$') assert.equal(d.search(p), words.some((w) => re.test(w))) } } })
wild.test.ts, continued: 3,000 random lists
✔ edge cases (0.8705ms) ✔ agrees with a regular expression on 3,000 random lists (29.9402ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
The edge cases are the empty pattern, which matches only a stored empty word, a single dot, which matches no empty word, a pattern longer or shorter than every word, and input outside a to z, which is rejected. Related on LeetCode: Design Add and Search Words Data Structure.
What does the search do at a dot?
- It tries every child of the current node with the rest of the pattern, and returns true as soon as one succeeds.
Part 6 · Every word in a letter grid
The problem
A word puzzle shows a grid of letters. A word can be traced by moving from a cell to a neighbour above, below, left or right, never using a cell twice in one word. Given a dictionary, find every word that can be traced.
The direct way is one search per word. For each word, start from every cell that holds its first letter and try to extend the path, backtracking when a neighbour does not match. Here is that search, with a counter of how many cells it enters.
Both searches keep the four moves in an array. They assume every row of the board has as many cells as the first row and that each cell holds one letter.
// The four moves: down, up, right, left. const STEPS = [[1, 0], [-1, 0], [0, 1], [0, -1]]
grid.ts: the four moves, down, up, right and left
// Can `word` be traced through neighbouring cells, using no cell twice? export function exists( board: string[][], word: string, stats = { calls: 0 }, ): boolean { const letters = Array.from(word) const rows = board.length const width = rows === 0 ? 0 : board[0].length const used = board.map((row) => row.map(() => false)) const go = (r: number, c: number, i: number): boolean => { stats.calls++ if (board[r][c] !== letters[i]) return false if (i === letters.length - 1) return true used[r][c] = true for (const [dr, dc] of STEPS) { const nr = r + dr const nc = c + dc const inside = nr >= 0 && nr < rows && nc >= 0 && nc < width if (inside && !used[nr][nc] && go(nr, nc, i + 1)) { used[r][c] = false return true } } used[r][c] = false return false } if (letters.length === 0) return false return board.some((row, r) => row.some((_, c) => go(r, c, 0))) }
grid.ts: can one word be traced in the board?
Its cost grows with the number of words, and most of the work is repeated: a hundred words beginning with st each walk the same cells for s and t again.
Walking the board and the trie together
Put the dictionary in a trie. Then search the grid once. From each cell, move to the child of the trie node that matches the cell's letter. If there is none, no word can pass through this cell on this path, so stop. If the node has the end flag, a word has been traced: record it. Then try the four neighbours, with the child as the new trie node.
Two details finish the job. A word must be reported once even if the grid holds it in several places, so clear the end flag when it is found. And dead branches should be cut: after exploring a node, if it has no children and no end flag, nothing below it can match any more, so delete it from its parent. Later searches then skip it without even looking.
// Every dictionary word that can be traced in the board. The board and // the trie are walked together, and branches no word can use are cut. export function findWords( board: string[][], words: string[], stats = { calls: 0 }, ): string[] { const trie = new Trie() for (const w of words) if (w !== '') trie.insert(w) const used = board.map((row) => row.map(() => false)) const rows = board.length const width = rows === 0 ? 0 : board[0].length const found: string[] = [] const path: string[] = [] const go = (r: number, c: number, parent: TrieNode): void => { stats.calls++ const letter = board[r][c] const node = parent.children.get(letter) if (node === undefined) return used[r][c] = true path.push(letter) if (node.end) { found.push(path.join('')) node.end = false // report each word once }
grid.ts: build the trie, then enter a cell
for (const [dr, dc] of STEPS) { const nr = r + dr const nc = c + dc const inside = nr >= 0 && nr < rows && nc >= 0 && nc < width if (inside && !used[nr][nc]) go(nr, nc, node) } path.pop() used[r][c] = false if (node.children.size === 0 && !node.end) { parent.children.delete(letter) // nothing below can match any more } } board.forEach((row, r) => row.forEach((_, c) => go(r, c, trie.root))) return found }
grid.ts, continued: neighbours, backtracking and pruning
// A 4 by 4 board of letters, one string per row. const board = ['pane', 'told', 'sira', 'meku'].map((row) => [...row]) const words = [ 'pane', 'pant', 'pole', 'told', 'sir', 'sire', 'mesa', 'top', ] // The result order is not promised, so sort it for display. console.log(findWords(board, words).sort())
A 4 by 4 board and eight candidate words
[ 'pane', 'sir', 'told' ]
Output of one run
Of the eight candidates, three can be traced: pane, sir and told. The others, such as pant and pole, run out of neighbours. The result order is not promised, which is why the demo sorts it. The recursion is as deep as the longest word, so there is no depth problem.
Counting the saving
The two methods are compared on a 20 by 20 board and 3,000 words over the letters a to d, with the same results from both. The counters count cells entered. Each method runs once beforehand so neither pays for a cold start.
// A 20 by 20 board and 3,000 words, all over the letters a to d. const rand = mulberry32(12) const letter = () => 'abcd'[Math.floor(rand() * 4)] const board = Array.from({ length: 20 }, () => Array.from({ length: 20 }, letter)) const words = Array.from({ length: 3000 }, () => Array.from({ length: 4 + Math.floor(rand() * 4) }, letter).join('')) // Run each once first so that neither pays for a cold start. void [...new Set(words)].filter((w) => exists(board, w)) void findWords(board, words) const one = { calls: 0 } let t = performance.now() const slow = [...new Set(words)].filter((w) => exists(board, w, one)) const oneMs = performance.now() - t const all = { calls: 0 } t = performance.now() const fast = findWords(board, words, all) const allMs = performance.now() - t console.log('words found:', fast.length, 'same set:', JSON.stringify(fast.sort()) === JSON.stringify(slow.sort())) const ms = (x: number) => x.toFixed(1) + ' ms' console.log(`one search per word: ${one.calls} calls, ${ms(oneMs)}`) console.log(`trie and board: ${all.calls} calls, ${ms(allMs)}`)
grid.cost.ts: calls and time for both
words found: 2202 same set: true one search per word: 459430 calls, 13.6 ms trie and board: 46036 calls, 8.6 ms
Output of one run; the times vary
The trie version enters about ten times fewer cells. The time falls by less, from 13.6 ms to 8.6 ms in the run above, and the time for the trie version includes building the trie. In six more runs here the first method took 12 to 23 ms and the second 9 to 13 ms. The saving grows with the size of the dictionary, since every new word costs one more search for the first method and only a few more nodes for the second.
const board = (rows: string[]) => rows.map((r) => [...r]) test('edge cases', () => { assert.deepEqual(findWords([], ['a']), []) assert.deepEqual(findWords(board(['ab']), []), []) assert.deepEqual(findWords(board(['a']), ['a', 'aa']), ['a']) assert.equal(exists(board(['a']), 'aa'), false) // no cell twice assert.equal(exists(board(['ab']), ''), false) // The order of the result is not promised, so sort before comparing. const square = findWords(board(['ab', 'cd']), ['abdc', 'acdb', 'ad']) assert.deepEqual(square.sort(), ['abdc', 'acdb']) // A repeated word in the list is reported once. assert.deepEqual(findWords(board(['ab']), ['ab', 'ab']), ['ab']) }) test('agrees with one search per word on 2,000 random boards', () => { const rand = mulberry32(95) const letter = () => 'abc'[Math.floor(rand() * 3)] for (let round = 0; round < 2000; round++) { const rows = 1 + Math.floor(rand() * 4) const cols = 1 + Math.floor(rand() * 4) const b = Array.from({ length: rows }, () => Array.from({ length: cols }, letter)) const words = Array.from({ length: Math.floor(rand() * 10) }, () => Array.from({ length: Math.floor(rand() * 6) }, letter).join('')) const want = [...new Set(words)].filter((w) => exists(b, w)).sort() assert.deepEqual(findWords(b, words).sort(), want) } })
grid.test.ts
All chapters · Previous: Tree Breadth-First Search: Level by Level