You are given a string S of length N and another string T of length M. These strings consist of lowercase English letters.
A string X is called a good string when the following conditions are all met:
Let L be the length of X. L is divisible by both N and M.
Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.
Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.
Determine if there exists a good string. If it exists, find the length of the shortest such string.
Constraints
1 \leq N,M \leq 10^5
S and T consist of lowercase English letters.
|S|=N
|T|=M
Input
Input is given from Standard Input in the following format:
N M
S
T
Output
If a good string does not exist, print -1; if it exists, print the length of the shortest such string.
Examples
Input
3 2
acp
ae
Output
6
Input
6 3
abcdef
abc
Output
-1
Input
15 9
dnsusrayukuaiia
dujrunuma
Output
45
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to determine existence of a string X such that its length L is a common multiple of N and M, and when we take every (L/N)-th character starting from position 1, we get S, and when we take every (L/M)-th character starting from 1, we get T.
Let's formalize. Define:
step_A = L / N. Then the positions for S: 1, 1+step_A, 1+2*step_A, ..., 1+(N-1)*step_A.
step_B = L / M. Positions for T: 1, 1+step_B, 1+2*step_B, ..., 1+(M-1)*step_B.
Thus X is a string of length L, with certain constraints at those positions.
Let’s denote indices from 1 to L inclusive.
We need to assign characters to positions that are in the union of two arithmetic progressions. There may be overlapping positions, where both S and T require a character; those must be consistent.
We need to find L, a common multiple of N and M, such that there exists an assignment satisfying the constraints.
Goal: existence, and if exists, minimal L.
Observation: This is reminiscent of "consistency of two patterns" or "interlaced strings". Actually it's similar to problem: given two strings S and T, we want to find a string X that when "downsampled" with step sizes gives S and T. The step sizes are determined by L.
Given L, the steps are step_A = L/N, step_B = L/M. Both integers.
Then the positions for S: i -> pos_S(i) = 1 + (i-1)*step_A for i=1..N.
Similarly pos_T(j) = 1 + (j-1)*step_B for j=1..M.
The condition for consistency: For any pair (i,j) such that pos_S(i) == pos_T(j), we need S[i] == T[j].
Thus the existence for a given L is equivalent to: for all i,j with 1+(i-1)*step_A = 1+(j-1)*step_B, S[i] == T[j].
Simplify: (i-1)*step_A = (j-1)*step_B.
Let d = gcd(step_A, step_B). Then the equation has solutions: (i-1) must be multiple of step_B/d, and (j-1) multiple of step_A/d, but more concretely, the positions where they coincide correspond to indices that are multiples of the lcm of steps? Actually, we have two arithmetic sequences starting at 1 with steps step_A and step_B. Their intersection set is {1 + k * lcm(step_A, step_B)}? Check: For two arithmetic sequences: start a=1, step=s; b=1, step=t. The intersection is positions p such that p ≡ 1 (mod s) and p ≡ 1 (mod t). This is p ≡ 1 (mod lcm(s,t)). So intersection = {1 + k * L0} where L0 = lcm(step_A, step_B). But note: the sequences each have finite length up to L, but we care about indices that are within 1..L.
Thus the overlapping indices are exactly of the form: 1 + q * L0, for integer q >= 0, as long as <= L.
Now, for each such overlapping position, there correspond specific i and j. How to map? p = 1 + (i-1)*step_A = 1 + (j-1)*step_B. So (i-1) = (p-1)/step_A, (j-1) = (p-1)/step_B. Both must be integers (they are). So condition S[i] == T[j] must hold for each such p.
Thus existence for a given L reduces to: For all q such that 1 + qL0 <= L, let i = 1 + qL0/step_A? Wait: (p-1) = q * L0. Then (i-1) = (qL0) / step_A. Since L0 = lcm(step_A, step_B), we have step_A divides L0, so i-1 = q * (L0/step_A). Similarly j-1 = q * (L0/step_B). So the overlapping positions correspond to indices i = 1 + q * A', where A' = L0/step_A, and j = 1 + q * B', where B' = L0/step_B. So essentially, the overlapping positions correspond to pairs (i, j) where i-1 is a multiple of A' and j-1 is a multiple of B'. But note: i runs from 1..N, j from 1..M. So we require that for any q such that i = 1 + qA' ≤ N and j = 1 + q*B' ≤ M, we have S[i] == T[j].
Now, note that L must be such that step_A = L/N, step_B = L/M. So step_A and step_B are determined by L. But L is a common multiple of N and M. Let L be any common multiple of N and M. Then step_A = L/N, step_B = L/M. So steps are positive integers.
We need to find L (common multiple) such that the consistency condition holds. And then among those, find the minimal L.
Observation: The consistency condition depends on step_A and step_B only through their ratio? Let's explore.
Let L be a common multiple of N and M. Write L = lcm(N,M) * k? Actually any common multiple is of the form L = L0 * t, where L0 = lcm(N,M). But careful: Because L must be a multiple of both N and M, the set of common multiples is multiples of lcm(N,M). So L = L0 * t, where t is a positive integer.
Now step_A = L/N = (L0 * t) / N. Since L0 = lcm(N,M) = N * M / g, where g = gcd(N,M). Then L0/N = M/g. So step_A = (M/g) * t. Similarly step_B = L/M = (L0 * t) / M = (N/g) * t.
So step_A = (M/g) * t, step_B = (N/g) * t, where g = gcd(N, M).
Thus steps are scaled by t.
Now L0 = lcm(N,M) = N*M/g.
We also have L = L0 * t.
Now compute L0' = lcm(step_A, step_B). step_A = a * t, step_B = b * t, where a = M/g, b = N/g. Note that a and b are coprime? Since gcd(a,b) = gcd(M/g, N/g) = 1 because we divided by g. Yes, a and b are coprime. Then step_A = a t, step_B = b t, with a,b coprime.
Then lcm(step_A, step_B) = lcm(a t, b t) = t * lcm(a, b) since t common factor? Actually lcm(a t, b t) = t * lcm(a, b) * (some factor?) More formally, since a and b are coprime, lcm(a, b) = ab. And lcm(a t, b t) = t * lcm(a, b) because any common multiple must be divisible by t and the lcm of a and b. However careful: If t has factors that may affect lcm? For example a=2, b=3, t=2: step_A=4, step_B=6, lcm=12 = 2 * lcm(2,3)?? lcm(2,3)=6, 26=12, yes. In general, since a and b are coprime, lcm(a t, b t) = (a t * b t) / gcd(a t, b t) = (a b t^2) / (t * gcd(a,b)) because gcd(a t, b t) = t * gcd(a,b) = t1 = t. So = a b t^2 / t = a b t. And a b = lcm(a,b) because a,b coprime. So lcm = t * a * b. So indeed L0 (call it L_overlap) = step_A * step_B / t? Actually abt = (M/g)(N/g)*t = (N M / g^2) * t. But also recall L = L0 * t = N M / g * t. So interesting relationship.
Now the overlapping positions are at p = 1 + q * L_overlap, where L_overlap = lcm(step_A, step_B) = a b t.
And the corresponding i and j indices: i = 1 + q * (L_overlap / step_A) = 1 + q * (a b t) / (a t) = 1 + q * b. Similarly j = 1 + q * (L_overlap / step_B) = 1 + q * a.
Thus overlapping positions correspond to q such that i = 1 + q * b ≤ N and j = 1 + q * a ≤ M.
Thus condition: For all integer q ≥ 0 such that 1 + q b ≤ N and 1 + q a ≤ M, we require S[1 + q b] == T[1 + q a].
Notice: This condition is independent of t! Because t canceled out. So the consistency condition depends only on a and b, which are determined by N and M (a = M/g, b = N/g), and the strings S and T. It does NOT depend on t (the multiplicative factor for L). That is surprising but plausible: The overlapping positions that arise are determined by the steps' ratio, not their absolute magnitude, as long as steps are scaled proportionally? Let's double-check: For a given L = L0 * t, step_A = a t, step_B = b t. Overlap positions occur at indices where both sequences land. The set of indices where both sequences land is {1 + k * lcm(step_A, step_B)} = {1 + k * a b t}. The corresponding S index is (1 + k * a b t - 1) / step_A + 1 = 1 + k * a b t / (a t) = 1 + k b. Similarly T index = 1 + k a. So indeed t cancels. So the condition for consistency is that for all k such that 1 + k b ≤ N and 1 + k a ≤ M, S[1 + k b] = T[1 + k a].
Thus the condition is independent of the choice of t. That means if there is any common multiple L = L0 * t that works, the condition must hold for the base case t=1 (i.e., L = lcm(N,M)). Conversely, if the condition holds for t=1, does it hold for any t? Let's examine: For a given t > 1, the overlapping positions are at indices 1 + k * (a b t). The condition requires that for each such k with valid indices, the characters match. The set of k that appear for t=1 is a subset? Actually for t=1, overlaps at positions 1 + k * a b (since t=1). For t>1, the overlaps are at positions 1 + k * a b t, which is a sparser set (since t > 1, the step is larger). The conditions for t=1 require checks at many k's, while for larger t, only a subset of those k (those where k is multiple of t? Wait careful: For t>1, the k index is integer; but the actual positions are multiples of a b t. That means the overlapping indices correspond to those q such that the index is 1 + q * a b t. Compare with t=1 overlapping indices: 1 + q' * a b. So the set for t>1 is a subset of the set for t=1 (because if we take q, the position is 1 + q * a b t = 1 + (q t) * a b, which is also an overlap for t=1 with k = q t). So the condition for t>1 is weaker; it only checks a subset of the constraints required for t=1. Therefore if the condition holds for t=1, it automatically holds for all larger t? Not exactly: For t>1, we also need to check that for k such that 1 + k b ≤ N and 1 + k a ≤ M, but now k corresponds to q? Actually for t>1, the overlapping indices are given by q (I'll call it q). The condition is for all q >=0 such that i = 1 + q b ≤ N and j = 1 + q a ≤ M (since i = 1+q b, j = 1+q a, independent of t), we need S[i] == T[j]. Wait but we derived i = 1 + q b, j = 1 + q a irrespective of t. That's because i = 1 + (q * L_overlap)/step_A = 1 + q*(a b t)/(a t) = 1 + q b. So indeed i depends only on q, not t. Similarly j = 1 + q a. So for each q that satisfies i ≤ N and j ≤ M, we need S[i] == T[j]. That set of q is exactly the same regardless of t! Because the condition i ≤ N and j ≤ M does not involve t. So the set of (i,j) pairs that must be consistent is the same for all t! Since i = 1 + q b, j = 1 + q a. As q ranges over integers >=0, we get the same pairs. The only difference could be that for larger t, the number of overlapping positions (i.e., the maximum q) is determined by the condition that the position itself ≤ L, not just i ≤ N and j ≤ M. However, note: The constraints on q from the string lengths: we need i ≤ N and j ≤ M for the strings S and T to have those indices. But if i > N or j > M, then that overlapping position would not correspond to a character in S or T? Actually if i > N, then the S sequence only goes up to N, but the overlapping position still exists in X; but does that require consistency? Let's think: The condition "concatenating the ... characters results in S" means that for i from 1 to N, the character at position pos_S(i) must equal S[i]. For i > N, there is no requirement because S has only N characters. Similarly for T. However, if an overlapping position corresponds to an index p that is in the set of positions for S? Actually for an overlapping position, p = pos_S(i) = pos_T(j) for some i and j. For the overlapping to be relevant, both i and j must be within their respective ranges. If p is such that it equals pos_S(i) for some i ≤ N and also pos_T(j) for some j ≤ M, then we require S[i] = T[j]. If p is pos_S(i) for i > N? But i > N is not defined because S has only N characters; but the position p may be still part of X? Actually the definition: The process of constructing X: we need to define characters at all positions 1..L. For positions that are not in either set? Actually every position in X is defined; we have freedom. But the constraints only apply to the positions that are used in the concatenation to form S and T. Specifically, we must ensure that for each i from 1 to N, X[1+(i-1)*step_A] = S[i]. For each j from 1 to M, X[1+(j-1)*step_B] = T[j]. If an index p is both 1+(i-1)*step_A and 1+(j-1)*step_B for some i and j, then it must satisfy both constraints, so S[i] must equal T[j]. However, if p is such that it is of the form 1+(i-1)*step_A but i > N? That can't happen because i is defined by the mapping: p corresponds to a specific i = (p-1)/step_A + 1. If that i > N, then p is still a position that would be used if S were longer? But S only provides constraints for i ≤ N. So for p such that (p-1)/step_A + 1 > N, there is no constraint from S on that position. Similarly for T. So overlapping positions only impose constraints when both i ≤ N and j ≤ M. So the set of relevant overlapping positions is exactly those q for which i = 1 + q b ≤ N and j = 1 + q a ≤ M.
Now, for a given L, are there overlapping positions where i > N or j > M? Possibly, but they don't impose constraints because at least one of the constraints doesn't exist. For example, if i > N but j ≤ M, then the position p is part of T's positions, but not S's. So there is only constraint from T: X[p] = T[j]. That's fine, no conflict. So only overlapping positions where both i and j are within range matter.
Thus the condition for existence of X for a given L is exactly that for all q with 1+q b ≤ N and 1+ q a ≤ M, we have S[1+q b] = T[1+ q a].
This condition does not involve t or L. So it is a necessary and sufficient condition for any L that is a common multiple of N and M? But wait, we also need to consider the possibility that for a given L, some positions might be assigned both constraints from S and T that are not captured by the above? Actually all positions that are both in S's set and T's set must satisfy the equation; we derived that those are exactly the ones with i = 1+q b, j = 1+q a. So that's the complete set of constraints. So if this condition holds, we can assign characters to all positions consistently: assign the required characters at positions that are only from S or only from T, and for overlapping positions assign that common character. There is no other cross constraint because the assignments are independent otherwise (no conflicts). So for any L that is a common multiple of N and M, the existence condition is exactly that the strings S and T are consistent on the "intersection indices" as defined by the sequences with steps a t and b t but as argued the set of relevant (i,j) pairs does not depend on t. So if the condition holds for one common multiple, it holds for all. Conversely, if it fails for the base (t=1), then for any larger t, the condition still requires that same set of (i,j) pairs? Let's verify: For t=2, the set of q such that i = 1+q b ≤ N and j = 1+q a ≤ M is the same as for t=1. Because q is just a variable. But is there any additional requirement that the overlapping positions must also satisfy that the position p is within L? Actually for q such that i≤N and j≤M, we also need that p = 1 + q * a b t ≤ L. But L = L0 * t = (N M / g) * t. Let's check: For q that yields i ≤ N, j ≤ M, is it guaranteed that p ≤ L? Since L is the total length. Let's see. For a given q, p = 1 + q * a b t. Since i = 1 + q b ≤ N => q b ≤ N-1 => q ≤ (N-1)/b. Similarly q ≤ (M-1)/a. Also, L = (N M / g) * t = N * (M/g) * t? Actually N M / g = N * a = M * b. Because a = M/g, b = N/g, so N * a = N * M/g = L0, and M * b = M * N/g = L0. So L = L0 * t = N * a * t = M * b * t.
Now p = 1 + q * a b t. We need p ≤ L. Is that automatically satisfied given i ≤ N and j ≤ M? Let's check maximum p for such q. The maximum q satisfying both i ≤ N and j ≤ M is q_max = min( floor((N-1)/b), floor((M-1)/a) ). Then p_max = 1 + q_max * a b t. We need p_max ≤ L = N a t? Actually L = N a t? Since L = N * step_A? step_A = a t, so L = N * step_A = N a t. Also L = M b t.
Check if for any q that satisfies i≤N and j≤M, p ≤ L automatically? Since i = 1+q b ≤ N => q b ≤ N-1 => q a b t ≤ a t (N-1) = N a t - a t. So p = 1 + q a b t ≤ 1 + N a t - a t = N a t - (a t - 1). Since a t ≥ 1, we have p ≤ N a t - something. But could it be > N a t? Not from that bound. Similarly from j: q a ≤ M-1 => q a b t ≤ b t (M-1) = M b t - b t = L - b t. So p ≤ L - b t + 1. So p ≤ L - (b t -1) < L. So indeed p < L (strictly less) for q_max? Actually if q_max = (N-1)/b exactly, then q b = N-1, so q a b t = a t (N-1) = N a t - a t, so p = 1 + N a t - a t = N a t - a t + 1. Since a t ≥ 1, p ≤ N a t = L, but might be equal to L only if a t = 1 and q b = N-1? Let's test: If a t = 1 and b = something, then p = 1 + (N-1)*? Actually a t = 1 => a = 1, t = 1. Then p = 1 + q b. With q = (N-1)/b? If b divides N-1, then p = 1 + N-1 = N, and L = N a t = N, so p = L. So possible that p_max = L. But that's okay because position L exists. So overall, for any q such that i ≤ N and j ≤ M, we have p ≤ L (since the maximum p is at most L). We should verify: From i ≤ N: q b ≤ N-1 => q a b t ≤ a t (N-1). Adding 1 gives ≤ a t (N-1) + 1. Since a t (N-1) + 1 ≤ a t N = L if and only if a t (N-1) + 1 ≤ a t N => 1 ≤ a t, which is true for positive integers. So indeed p ≤ L. Similarly from j. So all overlapping positions that matter are within L. So the condition is independent of t.
Thus the existence condition is purely that for all q >= 0 with 1 + q b ≤ N and 1 + q a ≤ M, we have S[1+q b] = T[1+q a]. This is equivalent to checking the characters at positions in S and T that are aligned via the "common pattern" determined by the ratio a:b.
Now, if this condition holds, then for any t >= 1, we can construct X of length L = lcm(N,M) * t that satisfies the requirements. So existence is determined by that condition. If it fails, no L works.
Therefore the problem reduces to checking this condition, and if true, find the minimal L. Since L can be any multiple of lcm(N,M), the minimal is L0 = lcm(N,M) (t=1). Wait, is t=1 always valid? Need to confirm that for t=1, the overlapping positions satisfy the condition as we assumed? But we deduced condition independent of t; if it holds, then t=1 works. So minimal L is lcm(N,M). However, is there a possibility that even if the condition holds, t=1 might not work because of some other constraint? Let's double-check thoroughly.
We have two arithmetic sequences: positions of S: P_S = {1 + (i-1)step_A} for i=1..N. For t=1, step_A = a, step_B = b. Overlaps: at positions where 1 + (i-1)a = 1 + (j-1)b => a(i-1) = b(j-1). Since a and b coprime, i-1 = bk, j-1 = ak for integer k >=0. Then i = 1 + bk, j = 1 + ak. We need i ≤ N, j ≤ M. For each such k, we need S[i] = T[j]. That's exactly our condition. So if condition holds, we can assign X accordingly: at those overlapping positions assign that character; at positions that are only from S assign corresponding S char; only from T assign T char; other positions (if any) are free? Wait, are there positions that are neither in the S set nor T set? Possibly, if L > Nstep_A? Actually L = Nstep_A = Na, and S positions exactly cover N*a positions? No, S positions are exactly N positions spaced step_A apart, so they cover N positions. They do not cover all positions unless step_A=1. Similarly for T. There may be positions not constrained at all; we can assign any character (say 'a') and it's fine. So indeed we can construct X. So t=1 works if condition holds.
But is there any possibility that t=1 leads to conflicting assignments because overlapping positions are not the only intersections? Overlaps are exactly where both sequences land. So yes.
Thus the minimal L is lcm(N,M). However, let's test with provided examples.
Example 1:
N=3, M=2.
S="acp", T="ae".
Compute g = gcd(3,2)=1.
a = M/g = 2, b = N/g = 3.
Check condition: For k>=0, i = 1 + kb = 1 + 3k ≤ 3 => k=0 only (i=1). j = 1 + ka = 1 + 2k ≤ 2 => k=0 only (j=1). So need S[1] == T[1] => 'a' == 'a' OK. So condition holds. Minimal L = lcm(3,2)=6. Output 6. Matches.
Example 2:
N=6, M=3.
S="abcdef", T="abc".
g = gcd(6,3)=3.
a = M/g = 3/3=1, b = N/g = 6/3=2.
Check k: i = 1 + kb = 1 + 2k ≤ 6 => k=0,1,2 (i=1,3,5). j = 1 + ka = 1 + 1*k ≤ 3 => k=0,1,2 (j=1,2,3). For k=0: i=1, j=1 => S[1]='a', T[1]='a' OK.
k=1: i=3, j=2 => S[3]='c', T[2]='b' => 'c' != 'b', fails. So condition fails, output -1. Matches.
Example 3:
N=15, M=9.
S="dnsusrayukuaiia", T="dujrunuma".
Compute g = gcd(15,9)=3.
a = M/g = 9/3=3, b = N/g = 15/3=5.
Check k: i = 1+5k ≤15 => k=0,1,2 (i=1,6,11). j = 1+3k ≤9 => k=0,1,2 (j=1,4,7). Need S[1] == T[1], S[6] == T[4], S[11] == T[7]. Let's check S indices: S[1]='d', T[1]='d' ok. S[6]? S string length 15, indexing 1-based: S = "d n s u s r a y u k u a i i a"? Actually let's write: positions: 1:d,2:n,3:s,4:u,5:s,6:r,7:a,8:y,9:u,10:k,11:u,12:a,13:i,14:i,15:a. So S[6]='r', T[4]? T="d u j r u n u m a": 1:d,2:u,3:j,4:r,5:u,6:n,7:u,8:m,9:a. So T[4]='r' matches. S[11]='u', T[7]='u' matches. So condition holds. Minimal L = lcm(15,9)=45. Output 45 matches.
Thus indeed the solution is: if condition holds, answer = lcm(N, M); else -1.
But wait, is there any nuance about the "shortest" good string? Could there be a shorter string than lcm(N,M) that still satisfies L divisible by both N and M? The length L must be a common multiple of N and M. The smallest positive common multiple is lcm(N,M). So if there exists any good string, the minimal possible length is at least lcm(N,M). Since we have shown that if condition holds, lcm(N,M) works, that is minimal. So answer is lcm(N,M). The only catch: Could there be a scenario where condition fails for lcm(N,M) but holds for some larger L? Based on our analysis, condition is independent of t. So if it fails for t=1, it fails for all t. So answer -1.
But is there any subtlety about overlapping positions when t is larger? We argued that the set of (i,j) pairs that are forced to match is the same for any t. But is it possible that for larger t, some overlapping positions would have i and j both within range but the position p might exceed L? Actually we already argued p <= L for those i,j. So all those pairs still need to be consistent. So condition must hold. Therefore necessary.
Thus problem is straightforward: compute g = gcd(N, M). Compute a = M/g, b = N/g. Then for all k from 0 up to min(floor((N-1)/b), floor((M-1)/a)), check if S[ bk ]? Actually index i = 1 + kb, j = 1 + k*a. Check S[i] == T[j]. If all equal, output lcm(N,M) = N * M / g. Otherwise -1.
But constraints: N,M up to 1e5, so straightforward iteration is fine: the number of checks is at most min(N/b, M/a) which is at most? Actually i = 1 + kb ≤ N => k ≤ (N-1)/b. Since b = N/g, (N-1)/b < g? Because N/b = N / (N/g) = g. So k < g. Similarly, (M-1)/a < g. So the number of k is at most g-1? Actually maximum integer k such that 1 + kb ≤ N is floor((N-1)/b). Since b = N/g, (N-1) / (N/g) = g * (N-1)/N < g. So floor is at most g-1. Similarly for M, at most g-1. So the total number of checks is ≤ g. Since g = gcd(N,M) can be up to 1e5, it's okay to iterate up to g. So O(g) time, which is fine.
But we need to be careful with 1-indexing. Strings are given as zero-indexed in input? Usually we treat them as 0-indexed for coding. So we can adjust: S[0] is first character, etc. Then indices: i = k * b (0-indexed: i = k * b) for k from 0 while kb < N? Wait using 0-index: S index i0 = i-1 = kb. Similarly T index j0 = ka. Condition: S[kb] == T[ka] for all k such that kb < N and k*a < M. That's simpler.
Thus algorithm:
Read N, M.
Read S, T.
Compute g = gcd(N, M).
Compute a = M // g, b = N // g.
For k from 0 while kb < N and ka < M:
if S[kb] != T[ka]:
print(-1) and exit.
If all match, compute L = N * M // g (since lcm = N*M/gcd), print L.
But wait: Is it always true that L = lcm(N,M) works? There is another nuance: The length L must be divisible by both N and M. That's satisfied. But also, the definition requires that concatenating the 1st, (L/N+1)-th, (2*L/N+1)-th, ... characters yields S. But does the order of characters in S correspond exactly to those positions? For L = lcm(N,M), step_A = L/N = a, step_B = L/M = b. And the positions are as described. That's fine.
Now, check if there is any extra condition: For t=1, we have step_A = a, step_B = b. Could there be a scenario where the positions from S and T overlap in a way that some position is required to be both S[i] and T[j] but the indices i and j are as derived, and we already check those. That's it.
But wait: The problem statement: "Concatenating the 1-st, (L/N+1)-th, (2*L/N+1)-th, ..., ((N-1)L/N+1)-th characters of X, without changing the order, results in S." That means we take the characters at positions: 1, 1+L/N, 1+2L/N, ..., 1+(N-1)*L/N. So it's exactly as we described.
Thus the solution appears trivial.
However, before finalizing, we need to consider any edge cases. For instance, if N=1 or M=1. Let's test.
Case N=1, M any. Then S length 1. Condition: g = gcd(1,M)=1. a = M, b = 1. Check k: kb < N? k1 < 1 => k=0 only. So condition: S[0] == T[0]. So if S[0]==T[0], answer = lcm(1,M) = M. Otherwise -1. Does that make sense? For N=1, we need X length L divisible by 1 and M, minimal L=M. Then step_A = L/N = M/1 = M. So the only S position is X[1] = S[0]. Step_B = L/M = M/M=1, so T positions are every position: X[1], X[2], ..., X[M] should equal T[1..M]? Wait careful: T length M, positions: 1, 2, ..., M? Actually step_B = 1, so positions are 1, 2, ..., M. So T requirement: X[1]=T[1], X[2]=T[2],..., X[M]=T[M]. S requirement: X[1] = S[1] (since only first position). So we need S[1] = T[1] and no other constraints. So indeed condition S[0]==T[0] is necessary and sufficient. And we can construct X: X[1]=S[0]=T[0], and X[2]=T[1], etc. Works. So answer M.
Case N=M. Then g = N, a = M/g = 1, b = N/g = 1. Condition: For k from 0 while k<N (since k< N and k< M), need S[k] == T[k]. So essentially S must equal T. Then answer lcm = N. That's intuitive: steps are both 1, so X must be the same as both strings, so S=T required, length N.
Case where g is large: e.g., N=100000, M=100000. Then g=100000, a=b=1. Check all positions, O(N) which is up to 1e5, fine.
But what about N=10^5, M=10^5-1? Then g = gcd(N, M) maybe small. The number of checks is at most g, which can be up to 10^5? Actually gcd could be 1. Then g=1, a=M, b=N. Then k=0 only, one check. So overall it's efficient.
Thus algorithm is O(N + M + gcd(N,M)) but essentially O(N+M) for input reading.
But is there any scenario where L must be larger than lcm because for L = lcm(N,M), the step sizes are a and b, but maybe there is an issue with overlapping positions beyond the last character of S or T? No.
So answer seems to be lcm if condition holds else -1.
Now, check if there could be a scenario where condition holds but lcm(N,M) is not divisible by N and M? It is by definition. So fine.
Wait, but problem statement: "Let L be the length of X. L is divisible by both N and M." So L must be a common multiple. lcm is the smallest positive common multiple. So minimal possible L is lcm, and if it works, answer is lcm.
Thus solution is straightforward.
But before concluding, we need to be absolutely sure that no additional constraints arise from the requirement that X is a string (any characters allowed) and that there is no conflict with positions that are constrained by both S and T but in a non-overlapping way? Already covered.
One more nuance: The definition says "concatenating the 1-st, (L/N+1)-th, (2*L/N+1)-th, ..., ((N-1)*L/N+1)-th characters of X, without changing the order, results in S." That means we take those characters in order and they should exactly match S. That's exactly what we used.
Thus implementation is trivial.
But I'm suspicious because the problem seems too simple. However, given examples, it matches. I've seen similar problems: It is essentially a problem about checking consistency of two strings under modular constraints, and the answer is lcm if possible else -1.
Let me think deeper: Could there be a scenario where for L = lcm(N,M), the positions for S and T do not cover all positions, but there is some conflict where a position is required to be a character from S and also a character from T, but our derived mapping might miss some because we assumed coprime steps? But we derived i-1 = bk, j-1 = ak because a and b are coprime. That's correct if steps are a and b. But note that steps a and b might not be coprime? Wait earlier we defined a = M/g, b = N/g, and indeed gcd(a,b)=1. So they are coprime. So the solution set for a(i-1)=b(j-1) is i-1 = bk, j-1 = ak. Good.
Thus condition holds.
Thus solution is straightforward.
However, I recall a known AtCoder problem "Good String" (or similar) where the answer is lcm(N, M) if condition else -1. Yes, I think it's from AtCoder ABC or something.
But there is a potential nuance: The condition we derived: for all k such that ka < M and kb < N, S[kb] == T[ka]. But note that we used zero-indexed: S[kb] corresponds to the (kb+1)-th character of S. But we need to ensure that the indices are within range. Since kb < N and ka < M, it's fine.
Now, is there any case where ka could equal M? For ka = M, then j index would be M+? Actually j = 1 + ka, so if ka = M, then j = M+1 > M, not valid. So we use <.
Thus implementation: loop k = 0; while kb < N and ka < M: check; if mismatch print -1; else compute lcm.
Edge Cases:
N and M up to 1e5, product up to 1e10, lcm could be up to 1e10 which fits in 64-bit (since N*M <= 1e10, within 2^63). So use 64-bit (long long in C++, int64 in Python fine).
In Python, compute lcm = N * M // g.
Complexity: loop up to min(N//b, M//a) = min(g, something) actually up to g. So at most 1e5 iterations, fine.
Now, verify with some random cases: e.g., N=4, M=6. g=2, a=3, b=2. Condition: k=0: S[0]==T[0]; k=1: kb=2<4, ka=3<6 => S[2]==T[3]; k=2: k*b=4 <4? No, 4 not <4, so stop. So need S[0]==T[0] and S[2]==T[3]. If holds, answer lcm=12.
Let's test constructing X for L=12, steps: step_A=12/4=3, step_B=12/6=2. S positions: indices 1,4,7,10. T positions: 1,3,5,7,9,11. Overlaps: 1 and 7? Check 1: both, need S[1]=T[1]; 7: pos 7 = 1+23? Actually S positions: 1,4,7,10. T: 1,3,5,7,9,11. Overlap at 1 and 7. At 1: i=1, j=1. At 7: i=3? Wait i for S: position 7 is 1+(i-1)3 => (7-1)/3+1 = 3 => i=3, so S[3]; j: (7-1)/2+1 = 4 => j=4, so T[4]. So condition S[3]==T[4] is needed, which matches our k=1: S[2] (0-index) is S[3] (1-index) and T[3] is T[4]? Actually careful: k=1 gives i = 1+1b=1+2=3, j=1+1a=1+3=4. So matches. Good.
Thus algorithm stands.
But there might be a twist: Could there be a shorter length L that is not a multiple of lcm(N,M) but still divisible by N and M? Actually divisible by N and M implies L is a multiple of lcm(N,M). So minimal is lcm. So that's correct.
Thus answer is simply lcm if condition else -1.
Now, implement in Python.
Potential pitfalls: Input reading: N, M on first line, then S and T on separate lines. Ensure to strip newlines.
Complexities fine.
Now, double-check with a few more examples:
N=2, M=4, S="aa", T="aaaa". g=2, a=2, b=1. Condition: k=0: S[0]==T[0]; k=1: kb=1<2, ka=2<4 => S[1]==T[2]; k=2: k*b=2<2? no. So need S[1]==T[2] as well. If S[0]=a, S[1]=a, T[2]=a, OK. Answer lcm=4. Check: L=4, step_A=2, step_B=1. S positions: 1,3. T positions: 1,2,3,4. Overlaps: 1 and 3. At 1: S[1]=a, T[1]=a; at 3: S[2]=a, T[3]=a. Works. Could there be a shorter L? L must be multiple of 2 and 4, so minimal 4.
N=2, M=4, S="ab", T="aaaa". Condition fails because S[1]!=T[2]? Actually S[1]=b, T[2]=a. So -1.
Now, what about case where condition holds but L = lcm may not be sufficient because the positions for S and T might conflict indirectly via transitivity? For instance, suppose there is a position p that is a S position and also a T position, but also the T position might be overlapping with another S position in a chain? But they are direct overlaps. No other constraints.
Thus final answer.
But I want to be thorough: The strings S and T are of lengths N and M. The definition of good string X does not impose any constraints on characters at positions not in the specified arithmetic progressions. So we can assign arbitrary characters to those positions. So no conflicts.
Therefore the problem is solved.
But hold on: There's a known trick: The condition we derived is necessary and sufficient for existence for any L that is a common multiple. However, is it possible that for some L, even if condition fails for some overlapping positions, we could still assign characters because the overlapping positions may not actually be required due to something like the same character being assigned from both sides but we could assign a character that satisfies both? No, if both constraints apply to same position, they must be equal to the specific characters from S and T. So they must match.
Thus condition is necessary.
Thus solution is correct.
Now, let's produce final answer.
But note: Some might think about the possibility of L not being exactly lcm but maybe some smaller L that is not a common multiple? Not allowed.
Thus code is simple.
We'll implement:
def solve():
import sys, math
input = sys.stdin.readline
N, M = map(int, input().split())
S = input().strip()
T = input().strip()
g = math.gcd(N, M)
a = M // g
b = N // g
# iterate k from 0 while kb < N and ka < M
# max_k = min((N-1)//b, (M-1)//a) but simply while loop
k = 0
while k * b < N and k * a < M:
if S[kb] != T[ka]:
print(-1)
return
k += 1
lcm = N // g * M # to avoid overflow? Python handles big ints, but safe.
# Actually N * M // g
print(N * M // g)
We need to ensure using integer arithmetic.
Edge: N*M might be up to 1e10, fine.
Test with given examples:
Example1: N=3 M=2 => g=1, a=2,b=3. k=0 only, S[0]='a', T[0]='a' ok => lcm=6 -> prints 6.
Example3: N=15 M=9 => g=3, a=3, b=5. k=0: S[0]=d, T[0]=d; k=1: S[5]=? index 5 (0-index) is 6th char? S[5] = character at position 6? Actually S indices: 0:d,1:n,2:s,3:u,4:s,5:r => 'r', T[3] = T[3] = 4th char? T[3]='r', ok; k=2: S[10]? 10th index? S[10] = 11th char: S[10]='u', T[6] = 7th char: T[6]='u', ok; k=3: 35=15 not <15? Since 15 < 15? Condition is kb < N, so 15 < 15 false, so stop. So all ok => lcm=15*9//3=45.
Works.
Now, consider a case where N and M have gcd > 1, but the condition holds for all k. For instance, N=4, M=6 as above, with appropriate S and T. Should output 12.
Now, could there be a case where condition holds but lcm is not enough because the positions for S and T require different characters at the same index in X but we think they match? Already checked.
So final answer.
Thus solution is O(N+M+gcd) which is okay.
We should also ensure that we are using 0-index correctly: S[kb] accesses the character at index kb. Since kb < N, it's safe. T[ka] similarly.
Now, provide explanation and final code.
But before finalizing, I want to consider if there is any possibility that L must be larger than lcm because of some "alignment" of characters that are not directly overlapping but due to transitive constraints? For instance, suppose position p is a S position and position q is a T position, but there is some other relationship linking them? The only constraints are direct assignments at specific positions. There is no relation between different positions. So no transitive constraints.
Thus solution stands.
Given the simplicity, the intended solution is likely this.
Now, produce final answer in the required format.
Thus final Python code.
But we also need to handle input reading with possible newline characters. Use .strip().
Implementation:
import sys
import math
def main():
data = sys.stdin.read().split()
# First two numbers, then S, then T
# Since S and T may contain newlines but split handles.
N = int(data[0])
M = int(data[1])
S = data[2]
T = data[3]
# Ensure lengths match? Not necessary.
g = math.gcd(N, M)
a = M // g
b = N // g
# Iterate
k = 0
while k * b < N and k * a < M:
if S[kb] != T[ka]:
print(-1)
return
k += 1
lcm = N // g * M # or N * M // g
print(lcm)
if name == "main":
main()
We should be careful: data[2] and data[3] are strings. They may be taken as separate tokens even if there are spaces? But strings consist of lowercase letters without spaces, so split works.
Alternatively, use sys.stdin.readline.
Now, final answer.
But wait: There is a subtle point: The condition we derived is for all k such that kb < N and ka < M. However, is it necessary that we also consider k such that kb = N? No because i = kb+1, so i would be N+1, which is out of range. So no.
Thus correct.
Thus solution is done.
Now, we might also need to consider the possibility of multiple overlapping positions due to the steps not being coprime? But we already established steps are at and bt with a,b coprime. So they are coprime relative? Actually for t>1, step_A = at, step_B = bt. Their gcd = t * gcd(a,b) = t, since a,b coprime. So they are not coprime unless t=1. But earlier we derived overlapping positions indices: p = 1 + q * lcm(step_A, step_B) = 1 + q * abt. But the mapping from q to i: i = 1 + q * (lcm/step_A) = 1 + q * (abt)/(at) = 1 + q * b. That holds regardless of t. So the set of i indices for overlaps is determined solely by b and q. But note: The overlapping positions are at p = 1 + q * ab*t. For q that yields the same i, p may differ, but i is same. So condition S[i] == T[j] is same. So indeed the condition is independent.
One more nuance: Could there be overlapping positions that are not captured by this q because of multiple representations? For instance, if steps have a common factor, there could be overlaps that are not at the lcm step? Let's double-check: Two arithmetic sequences with steps s and t (starting at 1) have intersection at positions congruent to 1 modulo lcm(s,t). That's the complete set. There are no other overlaps. So correct.
Thus done.
Thus answer is lcm(N,M) if condition else -1.
Now, produce final answer.
But wait, there's a known AtCoder problem "ABC 135 C" something? Not sure.
Anyway, final answer. ```python
import sys
import math
def solve() -> None:
data = sys.stdin.read().split()
if not data:
return
N = int(data[0])
M = int(data[1])
S = data[2]
T = data[3]
code
g = math.gcd(N, M)
a = M // g # step factor for T indices
b = N // g # step factor for S indices
# check consistency on overlapping positions
k = 0
while k * b < N and k * a < M:
if S[k * b] != T[k * a]:
print(-1)
return
k += 1
# all overlaps consistent → shortest length is lcm(N, M)
lcm = N // g * M # same as N * M // g
print(lcm)