Naive Implementation

This is also known as a keyword tree, but it accomplishes the same task.

Naive

Disadvantages:

  • Not compressed, traversals are redundant in some parts.

  • Use of literal characters rather than indices, so its also not space efficient.

  • O(n2)O(n^2) time complexity. For construction of single word of size P|P|, every nn suffixes of quantity PP are inserted character by character by traversing down through the tree.

Advantages:

  • Less error prone

  • Simple to implement

  • Works

Output

Implementation Details

How this algorithm works can be summarized in the _insert method. Basically, we are recreating a trie with a few minor changes such as the special character delimiter, and insertion of additional suffixes.

A trie is essentially a n-ary tree. Since we know that each node that carries a character is guarenteed to be unique, we can substitute a vector with an unordered_map. For each word that gets inserted, its characters guide its traversal down the tree. If no node is found, a new one gets created. The leaf nodes, indicated by the special character delimiter carry the occurrences of a suffix.

Last updated

Was this helpful?