Professional Documents
Culture Documents
It'sastringproblemIhavebeenmakingonHackerrank.Itisexecutingfineonalltestcasesexcept
thelasttwo.Theselasttwotestcasearedeclaringit"Terminatedduetotimeout".
Cprogramsareallowed2secondsonthissiteandsomehowmyprogramistakingafractionbeyond
2seconds.HowamIsupposedtoreducethattimetaken?
FortwostringsAandB,wedefinethesimilarityofthestringstobethelengthofthelongestprefix
commontobothstrings.Forexample,thesimilarityofstrings"abc"and"abd"is2,whilethe
similarityofstrings"aaa"and"aaab"is3.
CalculatethesumofsimilaritiesofastringSwitheachofitssuffixes.
#include<stdio.h>
#include<string.h>
voidstringMatch(charstrMain[]){
intsimilarity=0,i,j;
for(i=0;i<strlen(strMain);i++){
for(j=0;j+i<strlen(strMain);j++){
if(strMain[j]==strMain[j+i]){
similarity++;
}else{
break;
}
}
}
printf("%d\n",similarity);
}
intmain(){
intT,i;
scanf("%d",&T);
charstr[1000000];
for(i=0;i<T;i++){
scanf("%s",str);
stringMatch(str);
}
}
optimization performance c
share improvethisquestion
strings programmingchallenge
editedJun16'14at18:21
200_success
72.3k
85
askedJun16'14at17:01
vaibhav
268
182
Theerrorshavegoneaway,sothishasbeenreopened.Pleaseremembertoincludeallcodesothatothers
cancompileandrunit.Jamal Jun16'14at17:31
addacomment
3Answers
Yourecalculatestringlengtheveryiterationofeveryloop:
active
oldest
votes
for(i=0;i<strlen(strMain);i++){
for(j=0;j+i<strlen(strMain);j++){
Itdoesnotlooklikethestringchangeslength.Socalculateitonce.
size_tsize=strlen(strMain);
for(i=0;i<size;i++){
for(j=0;j+i<size;j++){
Ordon'tevencalculateitatall.Thestringisterminatedwhenyoureachthe'\0'charactersojustlook
forthat
for(i=0;strMain[i];i++){
for(j=0;strMain[j+i];j++){
TheotherthingInoticedisthatyouarecheckingthestringagainstitself.Whichisnotsimilartothe
descriptionyougiveabove(whereyouarecomparingtwodifferentstrings).
share improvethisanswer
editedJun16'14at17:52
answeredJun16'14at17:46
LokiAstari
40.5k
41
137
YoursolutiontakesO(L3)time,whereListhelengthofthestring.Therearetwolevelsofforloops,
eachofwhichisO(L).However,youcall strlen() repeatedly,and strlen() isO(L).Youshouldn't
needtocall strlen() atallofyoujustlookforthe \0 terminatorasyouiterate.Thatwouldbringit
downtoO(L2).
However,whatyoureallyneedisasmarteralgorithm.Asithappens,Ireviewedjustsuchan
algorithmafewdaysago,calledtheZAlgorithm,whichreturnsanarrayofthelengthsofselfsimilar
prefixes.ThatshouldworkinO(L)timeandO(L)space.
share improvethisanswer
editedJun16'14at18:18
answeredJun16'14at18:06
200_success
72.3k
85
268
addacomment
Theproblemwiththeslowrunningtimeisduetothepresenceoftwoloopsinyourcode.Inthis
particularcase,onlyonesuffices.Thefollowingcodeshouldbefastenoughtopassyour
benchmarkingtest.
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<assert.h>
/*Headendshere*/
intcommonPrefix(char*a,char*b){
char*x,*y;
for(x=a,y=b;*x&&*y;x++,y++){
if(*x!=*y)
break;
}
returnxa;
}
intstringSimilarity(char*a){
intlen=strlen(a);
char*suffix;
inti,sum=0;
for(i=1;i<=len;i++){
suffix=a+leni;
sum+=commonPrefix(a,suffix);
}
returnsum;
}
intmain(){
intres,t,i;
scanf("%d",&t);
chara[100001];
for(i=0;i<t;i++){
scanf("%s",a);
res=stringSimilarity(a);
printf("%d\n",res);
}
share improvethisanswer
editedJun16'14at18:34
Jamal
25.4k
answeredJun16'14at17:43
Debasis
91
188
311
1 Don'tjustdumpyourcodeherefortheOPtouse.ExplainwhatyouchangedspecificallyandwhytheOP
shouldchangeittothewayyouhaveit.syb0rgJun16'14at22:02
Inmypreviouscode,IonlywrotethecommonPrefixfunction.Imissedhisquestionofaddressingtheself
similarity,thefunctionforwhichisnowaddedinthenewcode.I'vecheckedthatthepastedcodepassesthe
Hackerranktest.DebasisJun16'14at22:35
1 Thenestedforloopsstillexist.You'vejusthiddenoneoftheminsideahelperfunction,that'sall.
200_success Jun17'14at1:56
@DebasisNopes,thissolutionisn'timprovingtime.forthelast2testcasesitistaking3seconds.Same
timemysolutionwastaking. vaibhav Jun17'14at3:53
addacomment