Time complexity for inserting all suffixes of a string into a ternary search tree?

330 Views Asked by At

enter image description hereI have a ternary search tree that contain all the suffixes of a word. What is the time complexity for construction and searching a word in this structure?

Example:

a word banana$, have the suffix banana$,anana$,nana$,ana$,na$,a$,$ and in lexicografical order $,a$,ana$,anana$,banana$,na$,nana$.

inserting all suffix in the ternary search tree in balanced form is: anana$,a$,$,ana$,na$,banana$,nana$.

1

There are 1 best solutions below

0
On

Generally speaking, the time required to insert something into a TST is O(L log |Σ|), where L is the length of the string and Σ is the set of allowed characters in your string. The reason for this is that adding each individual character takes time O(log |Σ|) because you're adding each character into a BST of at most |Σ| elements. For the example you're describing, you're adding in strings of length 1, 2, 3, ..., n, so the runtime is O(n2 log |Σ|).

That said, I think you can speed this up by going through a more indirect route. A ternary search tree can be thought of as a trie where the child pointers of each node are stored in a binary search tree. If you just want a trie of all the suffixes, you might want to look at suffix trees, which are specifically designed to represent that information. They can be built in time O(n) for a length-n string.