16/35
Part 5 of 7 · Every suffixLearn

Every suffix in one trie

Level 2 of the practice problem asks about fragments from anywhere in a name, and a trie only answers prefixes. One observation fixes that, so that one trie holds them all:

The suffixes of lantern, each with a fragment that starts it
lantern
lantern
antern
antern
ntern
ntern
tern
tern
ern
ern
rn
rn
n
n

Green: lan, an, nte, ter, er, rn and n, each the start of a suffix.

Every fragment of a name is a prefix of one of its suffixes. ter in lantern is how the suffix tern starts. So insert every suffix, and every fragment becomes a path from the top.

Sedgewick and Wayne's Algorithms book gives the same trick for substring search. Their trie is laid out as a TST, a ternary search trie, which is another way to arrange a trie's nodes.

Put a count on each node: the number of names that contain its fragment. A name's shortest fragment that no other name contains is then the shortest walk, from any starting letter of the name, down to a node whose count is 1.