Source Code
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define ii pair <int,int>
#define F first
#define S second
#define ever (;;)

const int N = 5010;

int n1,n2,all;
char A[N],B[N];
string s1,s2;

pair < string , bool > ok(int from1,int from2)
{
    if( from1 > n1 || from2 > n2 )
        return { "" , 0 };

    string s3,s4;
    for(int i=0;i<from2;i++)
        s3 += s2[i];
    for(int i=0;i<from1;i++)
        s3 += s1[i];

    for(int i=from2;i<n2;i++)
        s4 += s2[i];
    for(int i=from1;i<n1;i++)
        s4 += s1[i];

    return { s3 , ( s3 == s4 ) };
}

int main()
{
    scanf("%s%s",&A,&B);
    s1 = A;
    n1 = s1.length();
    s2 = B;
    n2 = s2.length();
    all = n1 + n2;

    if( all&1 )
    {
        printf("-1\n");
        return 0;
    }

    if( s1 == s2 )
    {
        printf("%s\n",s1.c_str());
        return 0;
    }

    for(int from2 = 0;from2 <= n2;from2++)
    {
        bool q;
        string s;
        tie(s,q) = ok(all/2-from2,from2);

        if( q )
        {
            printf("%s\n",s.c_str());
            return 0;
        }
    }

    printf("-1\n");
}
Copy
Right into Two Naseem17
GNU G++17
116 ms
920 KB
Accepted