Search code examples
algorithmsuffix-tree

How to find the position of a substring in a large string using suffix tree algorithm?


I learned how to implement suffix tree from another stack overflow post. I can only know whether the substring exist of not. I want to know if there is a way to find the location of the sub pattern in the string using the suffix tree.


Solution

  • Yes! Suffix tree leaves are typically annotated with the index at which the given suffix starts. Consequently, you can find all occurrences of a string P in a string T by building a suffix tree for T, searching for P, then doing a DFS starting at the node the search ends at. Every leaf found this way corresponds to one index where the string P appears. Plus, this runs really fast: the runtime is O(|P| + k), where k is the number of matches.