I was solving a question and was getting constant TLE's, then I searched for the solution online and found the exact code was working flawlessy except there was one difference and that was char array and strings.
Looked up about the performance difference of these two DS but couldn't find anything that of that help.
Char array gives a time of 31ms on an online judge. Meanwhile the string one gives a TLE(2000ms). The maximum characters inputted are of size 131072.
Code snippet of char array :
char s[131073];
int getScore(int l, int r,char curr)
{
int score = 0;
for(int i=l; i<r; i++)
if(s[i]!=curr)
score++;
return score;
}
int dnc(int left, int right, char curr)
{
if(left == right) return 0;
if(right == left+1) return s[left]==curr ? 0 : 1;
int mid = (left+right)/2;
return min(getScore(left,mid,curr) + dnc(mid,right,curr+1),getScore(mid,right,curr) + dnc(left,mid,curr+1));
}
String code :
int getScore(string s, int l, int r,char curr)
{
int score = 0;
for(int i=l; i<r; i++)
if(s[i]!=curr)
score++;
return score;
}
int dnc(string s, int left, int right, char curr)
{
if(left == right) return 0;
if(right == left+1) return s[left]==curr ? 0 : 1;
int mid = (left+right)/2;
return min(getScore(s,left,mid,curr) + dnc(s,mid,right,curr+1),getScore(s,mid,right,curr) + dnc(s,left,mid,curr+1));
}
Solution Link: https://codeforces.com/contest/1385/submission/144376401 (TLE) https://codeforces.com/contest/1385/submission/144376593 (AC)