I was solving DISTINCT SUBSTRING (given a string, we need to find the total number of its distinct substrings).
I am using trie of suffixes to solve it.
I am passing the test cases, but getting TLE
when I submit. Also, the space consumed is very large, at 4093M
.
Note: Since there can be 256 char in total, I am setting an array size of 257, and the ascii value is acting as the index.
What I am thinking now:
for(int i=0;i<p;i++){
string temp = str.substr(i,p-i);
insert1(root,temp);
}
Since substr()
may take O(n) time, in the worst case insert function also takes
(n) time in the worst case, and O(n) for loop: O(n^3). This is getting me TLE.
error: could not convert 'temp' from 'std::__cxx11::string* {aka std::__cxx11::basic_string*}' to 'std::__cxx11::string {aka std::__cxx11::basic_string}'| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
So I am thinking to replace substr()
by something like this:
for(int i=0;i<p;i++){
string *temp = &str[i];
insert1(root,temp);
} ///and it is giving me error please suggest here what is the mistake and what to do
So that I can save O(n) time.
Please tell me how can I modify my trie approach so it gets accepted.
#include<iostream>
#include<string>
using namespace std;
const int alphabetsize = 257;
int cnt=0;
struct trienode{
struct trienode* children[alphabetsize];
bool isendofword;
};
struct trienode *getnode(void){
struct trienode *newnode = new trienode;
newnode->isendofword = false;
for(int i=0;i<alphabetsize;i++){
newnode->children[i]=NULL;
}
return newnode;
}
void insert1(struct trienode* root,string &key){
struct trienode *temp = root;
for(int i=0;i<key.length();i++){
int index = key[i];
if(!temp->children[index]){
temp->children[index]=getnode();
cnt++;
}
temp = temp->children[index];
}
temp->isendofword=true;
}
int main(){
int t;
cin>>t;
while(t--){
cnt=0;
string str;
cin>>str;
int p = str.length();
struct trienode* root = getnode();
for(int i=0;i<p;i++){
string temp = str.substr(i,p-i);
insert1(root,temp);
}
cout<<cnt<<endl;
}
}
error: could not convert 'temp' from 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' to 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
– PhonetistO(n^2)
. – Enrich