Count of distinct substrings | Practice | GeeksforGeeks

Given a string of length N of lowercase alphabet characters. The task is to complete the function countDistinctSubstring(), which returns the count of total number of distinct substrings of this string.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains a string str.
Output:
For each test case in a new line, output will be an integer denoting count of total number of distinct substrings of this string.
User Task:
Since this is a functional problem you don't have to worry about input, you just have to complete the function countDistinctSubstring().
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 1000
Example(To be used only for expected output):
Input:
2
ab
ababa
Output:
4
10
Exaplanation:
Testcase 1: For the given string "ab" the total distinct substrings are: "", "a", "b", "ab".
 
0
theanmolmalik2 months ago
C++ Solution using Trie
 
class Node
{
    public:
        bool isWord;
        Node* child[26];
        
        Node()
        {
            isWord=0;
            for(int i=0;i<26;i++)
            {
                child[i]=0;
            }
        }
};

int countDistinctSubstring(string s)
{
    Node* head=new Node();
    
    int count=1;
    
    for(int i=0;i<s.size();i++)
    {
        Node* temp=head;
        
        for(int j=i;j<s.size();j++)
        {
            if(temp->child[s[j]-'a']==NULL)
            {
                temp->child[s[j]-'a']=new Node();
                temp->isWord=1;
                count++;
            }
            
            temp=temp->child[s[j]-'a'];
        }
    }
    
    return count;
}
+1
ashiqhussainkumar1432 months ago
struct Node {   Node *ref[26];   bool flag=false;      void setEnd(){       flag=true;   }   bool containsKey(char c){       return ref[c-'a']!=NULL;   }   Node *get(char c){       return ref[c-'a'];   }   void put(char c ){       Node *node=new Node();       ref[c-'a']=node;   }};
 
int countDistinctSubstring(string s){   //Your code here  int count=0;  struct Node *root=new Node();    for(int i=0;i<s.length();i++){            struct Node *node=root;      for(int j=i;j<s.length();j++){                    if(!node->containsKey(s[j])){              node->put(s[j]);              count++;          }          node=node->get(s[j]);      }      node->setEnd();  }  return count+1;}
0
piyushsharma9129126 months ago
@geeksforgeeks please provide exact constrain, time complexity and space complexity of this problem. 
0
shivam__996 months ago
//simple trie solution
class Node {
  public:
  char data;
  unordered_map<char,Node*> m;
  bool isTerminal;
  Node(char ch)
  {
      data=ch;
      isTerminal=false;
  }
};

class Trie{
    
  public:
  Node * root;
  Trie()
  {
      root=new Node('\0');
  }
};

int countDistinctSubstring(string s)
{
    int cnt=1; //included count of substr " "
    Trie t;
    
    for(int i=0;i<s.size();i++)
    {
        Node* temp=t.root;
        for(int j=i;j<s.size();j++)
        {
            if(temp->m.count(s[j])==0)
            {
                Node* n=new Node(s[j]);
                temp->m[s[j]]=n;
                cnt++;
            }
            temp=temp->m[s[j]];
            if(!temp->isTerminal)
            temp->isTerminal=true;
            
        }
    }
    return cnt;
    
}
0
wallflower9 months ago
wallflower
Java trie solution. Just insert all suffixes in trie.https://ide.geeksforgeeks.o...
+1
Suryan Jain10 months ago
Suryan Jain
Python 1.18
def countDistinctSubstring(s):    #code here    ans=set()    n=len(s)    for window in range(n):        i=0        for j in range(window,n):            ans.add(s[i:j+1])            i+=1                return len(ans)+1
0
Shivam Jha10 months ago
Shivam Jha
Why am i getting SIGABRT error in this?class Trie{  public:   vector<trie*>child;  bool isend;  Trie(){      isend=false;      child=vector<trie*>(26,NULL);  }};    void insert(char key,Trie *root,string s){        Trie * curr= root;        int index=key-'a';        curr->child[index]=new Trie();        curr->child[index]->isend=true;        curr=curr->child[index];        for(int i=0;i<s.size();i++){ int="" index="s[i]-'a';" if(curr-="">child[index]==NULL){                curr->child[index]=new Trie();            }            curr=curr->child[index];            curr->isend=true;        }    }    bool search(Trie *root, string key){        Trie *curr=root;        for(int i=0;i<key.size();i++){ int="" index="key[i]-'a';" if(curr-="">child[index]==NULL) return false;            curr=curr->child[index];        }        return (curr!= NULL and curr->isend);    }    int distinct(Trie *root){        int count = 0;        for (int i = 0; i < 26; i++) {             if (root->child[i] != NULL) {                 count += distinct(root->child[i]);             }         }         return count + 1;     }int countDistinctSubstring(string s){    // total no of non empty substring of any string of n length will be n*(n+1)/2    // if empty is included then total will be = n* (n+1)/2 +1;    // unordered_set<string> st;    // int n=s.size();    // for(int i=0;i<n;i++){ for(int="" j="1;j&lt;=n-i;j++){" if(st.count(s.substr(i,j)))="" continue;="" st.insert(s.substr(i,j));="" }="" }="" return="" st.size()+1;="" trie="" *root="new" trie();="" int="" n="s.size();" string="" temp="" ;="" for(int="" i="0;i&lt;n;i++){" if(search(root,temp+s[i]))="" continue;="" insert(s[i],root,s.substr(i));="" temp.pop_back();="" }="" return="" distinct(root);="" <="" code="">
0
Adarsh Gautam11 months ago
Adarsh Gautam
Execution Time:0.31 Using Trie Only
0
Mustafa Basit1 year ago
Mustafa Basit
using Trieclass GfG{    static class TrieNode {         TrieNode childrens[];        boolean isEnd;         TrieNode() {             childrens = new TrieNode[26];             isEnd = false;         }     }     static void insertString(TrieNode root, String S) {         TrieNode node = root;         for(int level = 0; level < S.length(); level++) {             if (node.childrens[S.charAt(level) -  'a'] == null){                 node.childrens[S.charAt(level) - 'a'] = new TrieNode();             }             node = node.childrens[S.charAt(level) - 'a'];          }         node.isEnd = true;      }     static int countNodes(TrieNode root) {         int count = 0;        for (int i = 0; i < root.childrens.length; i++) {             if (root.childrens[i] != null) {                 count += countNodes(root.childrens[i]);             }         }         return count + 1;     }    public static int countDistinctSubstring(String S)   {       //your code here       TrieNode root = new TrieNode();       for (int i = 0; i < S.length(); i++) {           insertString(root, S.substring(i));       }       return countNodes(root);    }}
0
Vikas Thapliyal
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.