1473B - String Lcm

Note that our lcm string, has to have size $lcm(a, b)$. Let’s just extend both $a$ and $b$ so that they have that size and then compare them.

Time complexity: $O(n)$

Memory complexity: $O(n)$

Click to show code.


using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
int main(void)
{
    ios::sync_with_stdio(false), cin.tie(NULL);
    int t;
    cin >> t;
    while (t--)
    {
        string a, b;
        cin >> a >> b;
        int n = a.size(), m = b.size(), l = lcm(n, m);
        a.resize(l), b.resize(l);
        for (int i = n; i < l; ++i)
            a[i] = a[i % n];
        for (int i = m; i < l; ++i)
            b[i] = b[i % m];
        cout << (a == b ? a : "-1") << endl;
    }
    return 0;
}