Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string.
Input : str = “ababa” Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa"
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.
Count of distinct substrings is 10
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count of distinct substrings of a string using Suffix Array
- Find distinct characters in distinct substrings of a string
- Count of substrings having all distinct characters
- Count number of substrings with exactly k distinct characters
- Count number of distinct substrings of a given length
- Count distinct substrings that contain some characters at most k times
- Count of substrings of length K with exactly K distinct characters
- Minimum changes to a string to make all substrings distinct
- Count of substrings of a binary string containing K ones
- Count the number of vowels occurring in all the substrings of given string
- Permutation of given string that maximizes count of Palindromic substrings
- Count number of substrings of a string consisting of same characters
- Queries to find the count of vowels in the substrings of the given string
- Given a binary string, count number of substrings that start and end with 1.
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Queries for number of distinct integers in Suffix
- Check whether count of distinct characters in a string is Prime or not
- Count ways to partition a string such that both parts have equal distinct characters
- String Range Queries to count number of distinct characters with updates
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
Improved By : Rajput-Ji