Microsoft Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Yeah, or vice versa, do srcsrc, which was my original answer. The follow up question then became, what if my src is huge and I don't want to concatenate it, what can you do -- Which I started thinking of using KMP for a partial match.
int findRotationIndex(const string & orig, const string & rot){
unsigned i=0;
unsigned orig_len = strlen(orig);
if(orig_len != strlen(rot))
return -1;
while(orig[i]){
unsigned j=0;
if(rot[j] == orig[i]){
for(unsigned k=i+1;k<orig_len;++k){
if(rot[++j] != orig[k]){
break;
}
}
if(k == strlen(orig)) return i;
else ++i;
}
else{
++i;
}
}
return -1;
}
So, O(n^2) time, but relatively good with space. I was using a KMP variant to get a partial match, and if the pattern also hits the end of the src, the starting index of the match is the rotation point. That way, I did it in O(m+k), however, I need extra space O(n) for the partial match table for KMP.
Append sch to itself. Find src in resultant string. The starting index of the src in the resultant string should be the rotation point.
Example:
src = tester
sch = sterte
Append sch to itself.
stertesterte
Find src in above string. Its the index-4 where the rotation point exists.
Let me know if understanding is wrong.
#include<stdio.h>
#include<string.h>
void removefirstchar(char * str)
{
int i =0;
for(i =0; i < strlen(str); i++)
{
str[i] = str[i+1];
}
}
int main()
{
char str[] = "TestOfTest";
char str1[] = "OfTestTest";
char *pos = NULL;
int length = strlen(str1);
int i =0;
for(i=length ; i>0; i--)
{
pos = strstr(str, str1);
if(i == length && pos)
{
printf("0");
return 0;
}
if(pos)
{
printf("%d\n", i);
return 0;
}
else
{
if(strlen(str1) > 1)
removefirstchar(str1);
}
}
printf("No rotation found");
}
#include<stdio.h>
#include<string.h>
void removefirstchar(char * str)
{
int i =0;
for(i =0; i < strlen(str); i++)
{
str[i] = str[i+1];
}
}
int main()
{
char str[] = "TestOfTest";
char str1[] = "OfTestTest";
char *pos = NULL;
int length = strlen(str1);
int i =0;
for(i=length ; i>0; i--)
{
pos = strstr(str, str1);
if(i == length && pos)
{
printf("0");
return 0;
}
if(pos)
{
printf("%d\n", i);
return 0;
}
else
{
if(strlen(str1) > 1)
removefirstchar(str1);
}
}
printf("No rotation found");
}
src = "hello"
- kill February 19, 2012sch = "lohel"
sch+sch = ""lohellohel"
src would always appear in sch + sch.
O(n) at the cost of O(n) extra space.
Otherwise you could just do a modified KMP algorithm on src and sch
Make sure that during comparisons when you move to the next character in sch, do (ch+1)%strlen(sch)