1

how to find that two strings are cyclic or not, in less than O(n^2) and without using a third array.
Input
str1 = "abcde" str="eabcd"
output
cyclic
Input
str1 = "cabdc" str="ccabd"
output
cyclic
Input
str1 = "ddabnhdd" str="dddabnhd"
output
cyclic

Please suggest me the best possible solution of it ???

r.bhardwaj
  • 1,603
  • 6
  • 28
  • 54

2 Answers2

4

You need to do an optimized string search, there are ones that take O(n) + O(m), you can find them here.
After that just double the first string and search the second in it, it will take O(n) time.
To avoid using a third array, just make every access to the first string modulo n.

Daniel
  • 30,896
  • 18
  • 85
  • 139
  • Doubling the first string is essentially the same as using a third array I think. – jahhaj Aug 04 '12 at 15:45
  • OK, but all those methods involve building a complex data structure in order to speed the search. I think the intent of the question is to do this without additional memory allocation. I might be wrong. – jahhaj Aug 04 '12 at 15:50
  • @dani what we will search in first string (first char of other or a substring of other string) ?? what we get after optimize string search please elaborate taking one example ! and intension is to find solution with better time complexity and of course without additional memory allocation ..... – r.bhardwaj Aug 04 '12 at 16:06
  • Is there any optimal string search algorithm that doesn't need any additional array? As far as I know algorithms like KMP all need an additional array. – lavin Aug 04 '12 at 19:13
3

The answer should be : minimal-cyclic-shift

The algorithm costs O(n) time and no additional array at all, and it finds the minimal cyclic shift of word.

using that, we can easily check :

int a=minLexCyc(str1),b=minLexCyc(str2),i,n=strlen(str1);
for(i=0;i<n;i++){
        if(str1[(a+i)%n]!=str2[(b+i)%n]){
                cout<< "not cyclic";
                return ;
        }
}
cout<< "cyclic";

PS: I don't think any solution that includes a searching string part will meet the requirement : without using a third array in O(n). So maybe the minimal-cyclic-shift solution is the only one.

Community
  • 1
  • 1
lavin
  • 2,276
  • 2
  • 13
  • 15
  • You should verify that both strings have the same length to avoid unpleasant surprises and possible wrong results, but good answer (I didn't know you could find the minimal cyclic shift in O(n) without an extra array, thanks for the link). – Daniel Fischer Aug 04 '12 at 21:25