Wednesday, October 16, 2013

[Amazon Interview] Longest substring

Given two string s1 and s2, find longest substring which is prefix of s1 as well as suffix of s2.

3 comments:

  1. #include
    #include
    #include


    char *findSubstring(const char *str1, const char*str2)
    {
    int len1 = strlen(str1);
    int len2 = strlen(str2);

    // find maximum length of common substring
    int n = 1;
    int max = 0;
    while (n <= len1 && n <= len2) {
    if (!strncmp(str1, str2 + len2 - n, n)) max = n;
    n++;
    }

    // create substring
    char *output = (char*)malloc(max+1);
    strncpy(output, str1, max);
    output[max] = '\0';

    return output;
    }

    int main()
    {
    const char *str1 = "ABCABCzzzzzzzzzzzzzzzzzzzzzzzzzzz";
    const char *str2 = "xxxxxxxxxxxxxxxABCABC";

    char *output = findSubstring(str1, str2);

    printf("[%s]\n", output);
    free(output);

    return 0;
    }

    ReplyDelete
  2. sahi hai KP :) ... you can stop loop after first unsuccessful match... example str1 = ABC is prefix of a very long string and str2 = DAB is suffix of a very long string then you can stop at after ABC and DAB match fails..... also for two long random strings with suffix and prefix not same.. you will continue till end of loop.

    ReplyDelete
  3. @Pankaj: Thanks for trying this question. But can u please elaborate as to where u want to break. As per ur commment, say str1 is "ABCzzzzzzzzzzzz"; and str2 is
    "xxxxxxxxxxxxABC". if we break after first unsuccesful match , then we will break at first index only and will never get the result. We need to continue till the end of the loop to find the longest matching substring.

    ReplyDelete