Google Interview Question
Country: United States
Interview Type: Phone Interview
str = "abcd"
substr = "cdc"
Function falis for above mentioned case. In detail, when first k character(k < substrlen) of substr matches with last k characters of str, this function fails.
Code can be corrected this way
const char* findSubstr(const char* str, const char* substr)
{
int len = strlen(str);
int substrlen = strlen(substr);
int j = 0;
const char* result = NULL;
for (int i = 0; i < len; ++i)
{
if (str[i] != substr[j])
{
j = 0;
result = NULL;
}
else
{
if (j==0)
result = &str[i];
++j;
if (j >= substrlen)
break;
}
}
if(j == substrlen)
return result;
else
return NULL;
}
I took a look at potentially fixing this to correctly return a substring, and came to the conclusion that if we iterated over every letter in the string, we could keep track of all potential substrings starting from whatever character we're currently looking at. If we find a mismatch, we can throw away that string and recurse using a string containing all characters except for those we have already proven do not contain that substring. Thoughts?
const char* findSubstr(const char* str, const char* substr)
{
int len = strlen(str);
int substrlen = strlen(substr);
int j = 0;
const char* result = NULL;
for (int i = 0; i < len; )
{
if (str[i] != substr[j])
{
j = 0;
result = NULL;
}
else
{
if (j==0)
result = &str[i];
++j;
++i;
if (j >= substrlen)
break;
}
}
if(j == substrlen)
return result;
else
return NULL;
}
There are some other interesting cases:
- Daniel Castro October 20, 20151. When the last unmatched character marks the beginning of the substring, it will fail. For example, let str = "babad" and substr = "bad".
2. More generally, the code does not handle the cases where the last analyzed characters donĀ“t match substr completely but match a prefix of substr. For example: str = "bababd", substr = "babd"