The idea is create a Trie of all suffixes of given string. Once the Trie is constricted, our answer is total number of nodes in the constructed Trie. For example below diagram represent Trie of all suffixes for “ababa”. Total number of nodes is 10 which is our answer.
How does this work?
Each root to node path of a Trie represents a prefix of words present in Trie. Here we words are suffixes. So each node represents a prefix of suffixes.
Every substring of a string “str” is a prefix of a suffix of “str”.
Below is implementation based on above idea.
// A C++ program to find the count of distinct substring
// of a string using trie data structure
#define MAX_CHAR 26
// A Suffix Trie (A Trie of all suffixes) Node
SuffixTrieNode() // Constructor
// Initialize all child pointers as NULL
for(inti = 0; i < MAX_CHAR; i++)
children[i] = NULL;
// A recursive function to insert a suffix of the s
// in subtree rooted with this node
// A Trie of all suffixes
// Constructor (Builds a trie of suffies of the given text)
root = newSuffixTrieNode();
// Consider all suffixes of given string and insert
// them into the Suffix Trie using recursive function
console.log('Count of distinct substrings is', countDistinctSubstring(str));
Count of distinct substrings is 10
Time Complexity:O(n2), where n is the length of string. Auxiliary Space: O(n)
We will soon be discussing Suffix Array and Suffix Tree based approaches for this problem. This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...