Learn / Tries

Word counting

Once words are in a trie, walking it answers questions about many words at once. Walking only through nodes that end a word finds the words whose every prefix is also a word; walking from each start position of a string finds every dictionary word that begins there.

How to recognise it

  • A dictionary and a long string to split into its words.
  • Words built one letter at a time from other words.
  • Several prefixes of one string must be checked against a word list.
cdaort
Words: car, cat, do. car and cat share the path c then a. Filled nodes end a word; every word through the a node starts with ca.

Words are stored in a trie first; then one walk answers the question.

Walks that answer questions

all prefixes present:  dfs from the root, entering a child only if it ends a word; keep the longest path
word break:            can[0] = true
                       for each i with can[i]: walk the trie along s from i; at every word end j: can[j + 1] = true
ProblemWalk
longest word with all prefixesthrough end nodes only
word break (trie)from every reachable start position

Common mistakes

  • Starting the word-break walk from positions that cannot be reached.
  • Forgetting that the empty prefix (the root) is always fine.

Problems

0 of 2 solved

Check yourself

For the longest word with all prefixes, which nodes may the walk enter?

In Word Break with a trie, what replaces checking each substring in a set?

Why visit children in letter order when breaking ties?