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.
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
| Problem | Walk |
|---|---|
| longest word with all prefixes | through 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
- Longest Word With All Prefixesmediumguide ready
- Word Break Problem | (Trie solution)mediumguide ready