![]() |
VOOZH | about |
Given two strings str1 and str2 of lengths N and M respectively. The task is to find the least common multiple (LCM) of both the strings and if it doesn't exist print -1.
Note: LCM of two strings is a string that can be formed by concatenating the strings to themselves and is shortest in length.
Examples:
Input: str1 = "baba", str2 = "ba"
Output: baba
Explanation: "baba" is the smallest string that can be obtained from both str1 and str2.
Notice that "babababa" can be also be formed but the length of the string is not least.
Input: str1 = "aba", str2 = "ab"
Output: -1
Explanation: No such string can be formed.
Approach: This problem is similar to finding shortest string formed by concatenating A x times and B y times. The task is solved by making lengths of both the strings equal and then checking whether both strings become the same or not. Follow the below steps to solve the problem:
Below is the implementation of the above approach:
baba
Time Complexity: O(N + M)
Auxiliary Space: O(N + M)