0

The code is as follows: The link to the question is : Two Strings

#include <bits/stdc++.h>

using namespace std;

// Complete the twoStrings function below.
string twoStrings(string s1, string s2) 
{
    long long int  i,j;
    long long int  m=s1.length();
    long long int n=s2.length();
    long long int dp[m+1][n+1];
    for(i=0;i<=m;i++)
    {
        for(j=0;j<=n;j++)
            dp[i][j]=0;
    }

    int count=0;
    for(i=0;i<=m;i++)
    {
        for(j=0;j<=n;j++)
        {
            if(i==0||j==0)
                dp[i][j]=0;
            else if (s1[i-1]==s2[j-1])
            {
                dp[i][j]++;
                count++;
            }
        }
    }

    if(count>0)
    {
        return "YES";
    }
    else
    {
        return "NO";
    }


}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int q;
    cin >> q;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    for (int q_itr = 0; q_itr < q; q_itr++) {
        string s1;
        getline(cin, s1);

        string s2;
        getline(cin, s2);

        string result = twoStrings(s1, s2);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}

It works perfectly for 6 out of 9 test cases. i don't think time is the problem here. it shows segmentation fault but doesn't elaborate on what actually the problem is. Any help would be appreciated. I can't figure out what the problem is

Chaitra
  • 27
  • 6
  • How big can `m` and `n` be? You could be running out of stack space; use `std::vector` instead. – 1201ProgramAlarm Jun 14 '20 at 21:56
  • `i<=m` is invalid. `m` is not a valid index in `s1`. With an array of `m` elements, the last index is `m-1`. Similar with `j`. You could instead of `count++;` just `return "YES"`. – KamilCuk Jun 14 '20 at 23:31

1 Answers1

1
  1. It's helpful to debug problems like this by testing locally, where you can add cout debugging statements throughout the code to figure out when the segfault occurs. If you can download the exact testcase which caused the failure, then you can run that locally.

  2. The problem statement states that the input sizes for the two strings can each be up to 10^5. If they are both 10^5, then the size of your DP array will be 10^5 * 10^5 = 10^10. 10^10 bytes is 10 gigabytes, which is likely more than what is allowed, and I think long longs are like 8 bytes? so it would be 80 GB.

  3. You seem to be vastly overthinking the problem. Consider the first example they give: s1 = hello and s2 = world, and the result should be true because these two words share a common substring: o. There should be a much simpler way to solve the problem than by comparing each character from s1 to each character to s2.

Kevin Wang
  • 2,188
  • 2
  • 8
  • 17
  • Thanks for the suggestions. I later realised that this program is not very efficient, Hence i wrote the program using the concept of hash table. – Chaitra Jun 15 '20 at 08:37