For ‘WORD’ = “abcd” and ‘N’ = 4 following are the 10 distinct substrings of ‘WORD’.
“abcd”, “abc”, “ab”, “a”, “bcd”, “bc”, “b”, “cd”, “c”, and “d”
If you are going to use variables with dynamic memory allocation then you need to release the memory associated with them at the end of your solution.
The first line of input contains an integer 'T' representing the number of test cases. Then the test cases follow.
The first line of each test case contains an integer ‘N’ representing the length of the string ‘WORD’.
The second line of each test case contains the string ‘WORD’.
For each test case, print the number of distinct substrings in the ‘WORD’
The output for each test case is printed in a separate line.
1 <= T <= 100
1 <= N <= 10 ^ 3
‘a’ <= WORD[i] <= ‘z’
Where ‘WORD[i]’ denotes the element at position ‘i’ in 'WORD'.
Time Limit: 1 sec
The basic idea behind this approach is to use a HashSet ‘ans’ to store all the possible substrings generated from the string ‘WORD’. Finally, we return the size of the HashSet.
Here is the complete algorithm:
The basic idea of this approach is the first iterate over this string ‘WORD’ and store all substrings of this string into a ‘TRIE’. Then iterate through this ‘TRIE’ and count how many words are there in the ‘TRIE’ that is our desired result.
The steps are as follows: