We need to compute minimal moves to make all strings equal by rotating each string (cyclic shifts) i.e., moving first character to end repeatedly. Each move corresponds to a left rotation by one character. So essentially we can rotate each string any number of times (cost = number of rotations mod length). We need to find a target string that is a rotation of each of the given strings, and minimize sum over strings of the minimal rotation distance to that target (where distance = number of left rotations needed to turn the original string into target). Since rotations are cyclic, we can consider each string's set of rotations (all possible strings after some number of moves). For the strings to be made equal, there must exist a string that appears as a rotation of every given string. That is, the intersection of all sets of rotations must be non-empty. If not, answer -1.
If there is at least one common rotation, we need to choose among these common rotations the one that minimizes sum of distances (i.e., minimal number of moves) from each original string to that rotation.
Observations: n ≤ 50, string length len ≤ 50. So we can brute force. For each string, we can generate all its rotations (there are len rotations). For each candidate rotation (which is a string), we can check if it exists in all strings' rotation sets. But we need to compute minimal sum of distances efficiently. Since len and n are small, we can do something like: For each rotation of the first string (consider that as candidate target), check if for every other string, it can be rotated to match that candidate. If yes, compute the total moves = distance from first string to candidate (which is some k) plus sum over others of minimal rotation distance to that candidate. But careful: The first string's distance to candidate is some k (0 <= k < len). But for others, we need minimal number of left rotations to reach candidate. Since rotations are reversible, we can compute for each string s, the minimal rotations needed to become target: we need to find shift d such that rotating s left by d yields target; if multiple? Actually for a given s and target that is a rotation of s, there is exactly one shift (if length L, and s and target are same string when rotated, there can be multiple if s has periodicity? Actually if the string has a period, then there could be multiple shifts that yield the same target? Example s = "aa", rotations: "aa", "aa". Both rotations produce "aa", but the shift values 0 and 1 both give "aa". So there can be multiple minimal rotations? But we want minimal number of moves, so we can choose the smallest d. But if there are multiple shifts, the minimal rotations is the smallest d such that rotate_left(s, d) = target. Since d can be from 0 to L-1. So we can compute minimal d. However, if the string has period p dividing L, then rotating by p yields same string; thus the set of rotations giving target might be arithmetic progression. But we can just compute minimal d.
But also note: Because moving first character to end repeatedly (left rotation) is our operation. So to get a target, we can rotate left d times, which is d moves. Or we can rotate right (which would be L-d moves) but we are only allowed left rotations. So we must consider left rotations only. So distance = minimal number of left rotations to achieve target. Since we can only do left rotations, we cannot rotate right directly. However, since we can rotate left many times, after L left rotations we get original. So to achieve a specific rotation that is d left rotations away, we can either do d left rotations, or d+L left rotations etc. So minimal is d mod L? Actually if we want a target that is equivalent to rotating left by d, we need to do d moves (if we define rotate_left(s, d) as moving first char to end d times). But there might be also alternative: rotate left by d+L, but that's more. So yes minimal d is the smallest non-negative integer such that rotate_left(s,d)=target.
But note: What if the target can be achieved by rotating right? For example, s = "ab", target = "ba". Rotating left by 1 yields "ba". Rotating right by 1 would be "ba" but we can't rotate right. So we need left rotations. So the distance is the smallest d such that rotate_left(s,d)=target. Equivalent to: the index shift such that target starts at position d of s (0-indexed) if we consider s as circular. More precisely, if s = s0 s1 ... s_{L-1}, then rotate_left(s, d) = s_d s_{d+1} ... s_{L-1} s_0 ... s_{d-1}. So target must equal that. So for a given s and target, we can compute all positions d where it matches. Then distance = min(d). So we can precompute for each string all rotations distances to each possible rotation string? But since len small, we can just brute force per candidate.
Simplest algorithm: For each candidate rotation of s1 (or any string), check if this candidate is a rotation of each other string. For each other string si, we need to find if candidate appears among its rotations; if yes, compute the minimal number of left rotations needed to achieve candidate. We can compute this by trying all d from 0 to L-1: if rotate_left(si, d) == candidate, record d and break. Then add d to sum. If for any si we never find a match, discard candidate. After checking all candidates, take the minimal total sum. Also consider that maybe the optimal target is not a rotation of s1? But if there is any common rotation, it must be a rotation of every string, so in particular it is a rotation of s1. So we only need to check rotations of s1 (or any string) as candidates. However, careful: Suppose s1 = "ab", s2 = "ba". Their rotations: s1 rotations: {"ab","ba"}, s2 rotations: {"ba","ab"}. So both are common rotations. So checking s1 rotations covers both "ab" and "ba". Good.
But what about strings with periods? Suppose s1 = "aa", s2 = "aa". All rotations are "aa". So candidate set includes "aa". Good.
Thus algorithm: Let n, and strings s[0..n-1]. Let L = len(s[0]) (all equal). For each shift d1 from 0 to L-1 (candidate = rotate_left(s[0], d1)), compute total_moves = d1? Actually careful: For s[0] itself, to get candidate, we need to rotate left by d1 moves. So that contributes d1 moves. However, we could also consider not rotating s[0] at all? But we must make all strings equal to some target; we could also choose target as s[0] itself (d1=0) or any rotation. So for each candidate, we compute total = (d1) + sum_{i=1..n-1} minRotDist(s[i], candidate). Note that minRotDist(s[0], candidate) = d1 if candidate = rotate_left(s[0], d1). But there might be other smaller d? No, because d1 is the specific shift we used to generate candidate; however if s[0] has periodicity, there may be smaller d that also yields candidate? Example: s[0]="aa", candidate "aa". Rotations: d=0 gives "aa", d=1 gives "aa". So minRotDist(s[0], "aa") = 0, not 1. So if we generate candidate using d1=1, we should not add 1 for s[0] because we could achieve the same string with 0 moves. But we are considering candidate as the string "aa". The fact we generated it via d1=1 doesn't mean s[0] must rotate 1; it could rotate 0 to get same string. So we must compute minRotDist(s[0], candidate) properly, not just d1. So it's better to compute minRotDist for each string individually. So for each candidate (which is a rotation of s[0]), compute total = sum_{i=0}^{n-1} minRotDist(s[i], candidate). Then take min over candidates that are valid (i.e., for every i, minRotDist exists). But we could also consider candidates that are rotations of other strings but not of s[0]; but as argued, any common rotation must be a rotation of s[0]. So covering s[0] rotations is sufficient.
So steps:
- For each shift d in [0, L-1]:
candidate = rotate_left(s[0], d)
total = 0
for i from 0 to n-1:
find min d_i such that rotate_left(s[i], d_i) == candidate; if none, break and invalid.
total += d_i
if valid, update answer = min(answer, total)
Complexity: n up to 50, L up to 50, so at most 50 candidates, each checking 50 strings, each trying up to 50 rotations: 505050 = 125k operations, trivial.
But careful: When a string has periodic structure, there may be multiple d_i values; we take the smallest. That's fine.
Edge cases: if answer remains INF (set initially large), output -1.
Examples:
Input1:
4 strings: xzzwo, zwoxz, zzwox, xzzwo
We need to compute. We'll test later.
We should also consider alternative: maybe the optimal target is not a rotation of s[0] if s[0] has duplicates? Actually any common rotation is a rotation of s[0]. So it's in the set of rotations of s[0]. So we cover all possibilities.
Implementation details: rotate_left(s, d): we can create string by taking substring from d to end + substring 0..d-1.
But careful about d=0: just the string itself.
We need to compute minRotDist for a given s and target. We can iterate d from 0 to L-1: if rotate_left(s, d) == target, return d. If none, return -1.
But we can also precompute for each string its rotations map from rotated string to minimal distance. Since L small, no need.
Potential pitfalls: The strings may be of length 0? Not allowed; length positive.
Now, check sample 1:
s1 = "xzzwo"
Rotations:
0: xzzwo
1: zzwox? Let's compute: left by 1: "zzwox"? Actually "xzzwo": remove first char 'x' => "zzwo" + "x" = "zzwox". So rotate_left(s1,1) = "zzwox".
2: "zwoxz"? rotate_left of "xzzwo" by 2: start from index 2: s[2]='z'? Actually indices: 0:x,1:z,2:z,3:w,4:o. So left by 2: positions 2,3,4,0,1 => "zwoxz"? Wait: s[2]='z', s[3]='w', s[4]='o', s[0]='x', s[1]='z' => "zwoxz"? Yes "zwoxz".
3: left by 3: positions 3,4,0,1,2 => "woxzz"? Actually s[3]='w', s[4]='o', s[0]='x', s[1]='z', s[2]='z' => "woxzz".
4: left by 4: positions 4,0,1,2,3 => "oxzzw"? Actually s[4]='o', s[0]='x', s[1]='z', s[2]='z', s[3]='w' => "oxzzw".
So rotations: xzzwo, zzwox, zwoxz, woxzz, oxzzw.
Now check other strings:
s2 = "zwoxz". Rotations:
0: zwoxz
1: woxzz? left by1: "woxzz"? Actually "zwoxz": indices:0:z,1:w,2:o,3:x,4:z. left1: positions1,2,3,4,0 => "woxzz"? w,o,x,z,z -> "woxzz".
2: left2: positions2,3,4,0,1 => "oxzzw"? o,x,z,z,w -> "oxzzw"? Actually careful: o,x,z,z,w -> "oxzzw"? yes.
3: left3: positions3,4,0,1,2 => "xzzwo"? x,z,z,w,o -> "xzzwo"? actually x,z,z,w,o -> "xzzwo"? yes.
4: left4: positions4,0,1,2,3 => "zzwox"? z,w,o,x,z? Wait positions4=z,0=z? Actually positions: 4:z, 0:z, 1:w, 2:o, 3:x => "zzwox"? z,z,w,o,x -> "zzwox"? yes.
So s2 rotations: zwoxz, woxzz, oxzzw, xzzwo, zzwox.
s3 = "zzwox". Rotations:
0: zzwox
1: zwoxz? left1: positions1,2,3,4,0 => z,w,o,x,z -> "zwoxz"? Yes.
2: woxzz? left2: positions2,3,4,0,1 => w,o,x,z,z -> "woxzz"? Yes.
3: oxzzw? left3: positions3,4,0,1,2 => o,x,z,z,w -> "oxzzw"? Yes.
4: xzzwo? left4: positions4,0,1,2,3 => x,z,z,w,o -> "xzzwo"? Yes.
s4 = "xzzwo" same as s1.
Now common rotations? Intersection of all sets appears to be maybe "zwoxz", "xzzwo", "zzwox", "woxzz", "oxzzw"? Let's check each:
- "xzzwo": appears in s1 (0), s2 (shift3), s3 (shift4), s4(0). So yes all have it.
- "zzwox": s1(1), s2(4), s3(0), s4(1). Yes.
- "zwoxz": s1(2), s2(0), s3(1), s4(2). Yes.
- "woxzz": s1(3? Actually s1 rotate3 is "woxzz"? Wait s1 rotate3 gave "woxzz"? We computed earlier: left3: "woxzz"? Actually we had left3 = "woxzz"? Check: s1 left3: positions3(w),4(o),0(x),1(z),2(z) => "woxzz"? That's w,o,x,z,z -> "woxzz". Yes. So s1(3), s2(1), s3(2), s4(3). Yes.
- "oxzzw": s1(4), s2(2), s3(3), s4(4). Yes.
All five rotations are common. So we need to compute total moves for each candidate.
We need min total moves. Let's compute:
For candidate "xzzwo":
- s1: minRotDist = 0 (since s1 itself). Actually check: s1 = "xzzwo", so d=0.
- s2: need to rotate to "xzzwo". From s2 rotations we found d=3 (since rotate left3 yields "xzzwo"). But also maybe other? Only d=3. So d=3.
- s3: need to rotate to "xzzwo". s3 rotate4 yields "xzzwo"? Actually s3 left4 gave "xzzwo"? Yes, we computed left4 = "xzzwo". So d=4? Wait check s3: string "zzwox". Left4: positions4=x? Actually positions: 0:z,1:z,2:w,3:o,4:x. Left4: indices4,0,1,2,3 => x,z,z,w,o = "xzzwo". So d=4. Also maybe left? Only one? So d=4.
- s4: s4 same as s1, so d=0.
Total = 0+3+4+0 = 7.
Candidate "zzwox":
- s1: d=1 (since left1 gives "zzwox")
- s2: d=4 (left4 gives "zzwox")
- s3: d=0 (s3 is "zzwox")
- s4: d=1
Total = 1+4+0+1=6.
Candidate "zwoxz":
- s1: d=2
- s2: d=0
- s3: d=1? Wait s3: "zzwox" left1 gives "zwoxz"? Yes, d=1.
- s4: d=2
Total = 2+0+1+2=5.
Candidate "woxzz":
- s1: d=3
- s2: d=1? Actually s2 left1 gives "woxzz"? Wait s2 left1 gave "woxzz"? Yes d=1.
- s3: d=2 (left2 gives "woxzz"? Actually s3 left2: we had "woxzz"? Yes d=2)
- s4: d=3
Total = 3+1+2+3=9.
Candidate "oxzzw":
- s1: d=4
- s2: d=2
- s3: d=3
- s4: d=4
Total = 4+2+3+4=13.
Min is 5. Matches sample output.
Great.
Second sample:
2 strings: "molzv" and "lzvmo"
s1 = "molzv" (len=5). Rotations? We'll compute distances.
Compute candidate from s1 rotations.
We need minRotDist for each.
Let's compute quickly:
s1 rotations:
0: molzv
1: olzvm? left1: remove 'm' -> "olzv" + "m" = "olzvm"
2: lzvmo? left2: start from index2: l? Actually s1: indices 0:m,1:o,2:l,3:z,4:v. Left2: l,z,v,m,o -> "lzvmo"? That's l,z,v,m,o -> "lzvmo". Yes.
3: zvm ol? left3: z,v,m,o,l -> "zvm ol"? Actually "zvm ol"? no spaces: "zvm ol"? But let's compute: indices3:z,4:v,0:m,1:o,2:l => "zvm ol"? That's "zvm ol"? Actually string: z v m o l => "zvm ol"? It would be "zvm ol"? But without spaces: "zvm ol"? Probably "zvm ol" is "zvm ol"? Actually it's "zvm ol"? Better: "z v m o l" => "zvm ol"? Let's concatenate: "z"+"v"+"m"+"o"+"l" = "zvm ol"? Actually that spells "zvm ol"? I think it's "zvm ol"? Wait maybe it's "zvm ol"? No, let's just write: characters: 'z','v','m','o','l' -> "zvm ol"? Actually that string is "zvm ol"? That doesn't look right. Possibly it's "zvm ol"? Let's ignore for now; we'll just compute. Actually it's "zvm ol"? Hmm, maybe it's "zvm ol"? That would be "z v m o l" => "zvm ol"? That would be "zvm ol"? I think the correct concatenation is "zvm ol"? Actually "zvm ol" is not a typical word but it's fine. I'll write "zvm ol"? Let's recalc: s1 = "molzv". So chars: m,o,l,z,v. Rotate left 3: take from index3: z, index4: v, index0: m, index1: o, index2: l -> so "z","v","m","o","l" => "zvm ol"? It's "z v m o l" => "zvm ol"? Actually that's "zvm ol"? No spaces: "z"+"v"+"m"+"o"+"l" = "zvm ol"? Wait, "zvm ol"? If I type "zvm ol" it's "zvm ol"? That's 6 characters? "zvm ol" includes a space? No. The string is "zvm ol"? I think it's "z v m o l" => "zvm ol"? Actually writing: z v m o l -> "zvm ol"? That's wrong: concatenating letters: z + v = "zv", + m = "zvm", + o = "zvmo", + l = "zvm ol"? That's "zvmo l"? Actually "zvmo"+"l" = "zvm ol"? I think it's "zvm ol"? Let's do step: "z"+"v" = "zv". "zv"+"m" = "zvm". "zvm"+"o" = "zvmo". "zvmo"+"l" = "zvm ol"? That's "zvm ol"? No, "zvmo"+"l" = "zvm ol"? That is "zvm ol"? Actually "zvmo"+"l" = "zvm ol"? That's "zvmo" + "l" = "zvm ol"? I'm confusing. Actually "zvmo"+"l" = "zvm ol"? Wait, "zvmo" is 4 letters, adding "l" gives 5 letters: z v m o l. So the string is "zvm ol"? No, it's "zvm ol"? The letters are z, v, m, o, l, so the word is "zvm ol"? But "zvm ol" is 6 characters? Because "zvm" would be 3, then space? Actually there is no space; it's just continuous: "zvm ol"? Let's just write it: "z"+"v"+"m"+"o"+"l" = "zvm ol"? That can't be right because "zvm ol" is 6 characters: z, v, m, space, o, l? Actually "zvm ol" as typed might be "zvm ol"? I think it's "zvm ol"? No, it's "z v m o l" -> typed as "zvm ol"? Actually if you type "zvm ol" without quotes, it's "zvm ol"? I realize I'm inserting a mental space. Actually the concatenation is "z"+"v"+"m"+"o"+"l" = "zvm ol"? No, the resulting string is "zvm ol"? I'm going to compute: Ascii: z (122), v (118), m (109), o (111), l (108). So the string is "\x7A\x76\x6D\x6F\x6C" which spells "zvm ol"? In text, "zvm ol" might appear as "zvm ol"? But "zvmo"+"l" = "zvm ol"? I'm going to stop this confusion: it's the string formed by characters: z, v, m, o, l. So it's "zvm ol"? Actually the correct string is "zvm ol"? I think it's "zvm ol"? No, "zvm ol" would be "zvm" then space then "ol". Let's just write: z v m o l -> that is "zvm ol"? That is not correct; the correct word is "zvm ol"? Hmm. Let's use a systematic approach: The string is "z" + "v" + "m" + "o" + "l" = "zvm ol"? That yields "zvm ol"? I'm now thinking that "zv" + "mo" = "zvmo", plus "l" = "zvm ol"? No, "zvmo" + "l" = "zvm ol"? Actually "zvmo" + "l" = "zvm ol"? That's incorrect: "zvmo"+"l" = "zvm ol"? Let's just actually type: z v m o l -> "zvm ol"? The word would be "zvm ol"? I'll break: After z, v, we have "zv". After adding m, it's "zvm". After adding o, it's "zvmo". After adding l, it's "zvm ol"? I think I'm inadvertently inserting a space. Actually "zvmo"+"l" = "zvm ol"? That is "zvmo" concatenated with "l" yields "zvm ol"? No, it's "z v m o l", so the sequence is: character1: 'z', char2: 'v', char3: 'm', char4: 'o', char5: 'l'. The resulting string is "zvm ol"? If I write these characters consecutively, I get "zvm ol"? That looks like "zvm ol"? But "zvm ol" is actually 6 characters: 'z','v','m',' ','o','l'. So it's not. I think the correct spelling is "zvm ol"? Actually "zvmo"+"l" = "zvm ol"? That's impossible because "zvmo" is 4 characters, plus "l" is 5, so the result is a 5-character string: positions: 1:z,2:v,3:m,4:o,5:l. That is "zvmo l"? Actually if you type "zvmo" and then "l", you get "zvm ol"? No, you get "zvm ol"? Let's just type: I'll open a mental text: "z" then "v" then "m" then "o" then "l". The result is "zvm ol"? But I think it's "z v m o l" -> that spells "zvm ol"? I'm going crazy. Let's just denote it as "zvm ol"? I think it's actually "zvmo l"? Hmm.
I realize: I'm reading "zvm ol" as having a space because "zvm" looks like a word, and "ol" looks like another, but there's no space. The actual concatenation is "z"+"v"+"m"+"o"+"l". If I write it as a continuous string, it's "zvm ol"? Actually "zvm ol" appears with a space? I'll write it: z v m o l -> that is "zvm ol"? When I type "zvm ol", it includes a space after "zvm". So no. Let's just represent as "zvmol"? Wait "zv"+"mo"+"l" = "zvmo"+"l" = "zvm ol"? No, "zvmo"+"l" = "zvm ol"? It would be "zvmo"+"l" = "zvm ol"? Actually "zvmo"+"l" = "zvm ol"? I'll compute step by step:
- Start with empty.
- Add 'z': "z"
- Add 'v': "zv"
- Add 'm': "zvm"
- Add 'o': "zvmo"
- Add 'l': "zvm ol"? That is "zvmo"+"l" = "zvm ol"? But "zvmo"+"l" should be "zvm ol"? If I write "zvmo" and then "l", I get "zvm ol"? That seems like "zvmo" and then "l" yields "zvm ol"? I think the problem is that I'm confusing the representation: In many fonts, the combination "ol" might look like a separate syllable, but there is no space. The string is simply "zvmo l"? Actually it's "zvmo" plus "l" gives "zvm ol"? Let's just treat as a string: chars: [z][v][m][o][l] -> it is "z v m o l" with no spaces. So the string is "zvmo l"? I'm overcomplicating. I'll simply denote it as "zvm ol"? No.
Maybe it's "zvmo l"? Actually, if we concatenate "z","v","m","o","l" we get "zvm ol"? The string "zvm ol" is 6 letters? Let's count: "z"=1, "v"=2, "m"=3, " "=4, "o"=5, "l"=6. So that's 6. So not that. It must be "zvmo l"? That would be "zvmo l" with a space? No.
I think the correct spelling is "zvmol"? That would be "z","v","m","o","l" -> "zvmol". Yes, that's it! I was misreading: concatenation yields "zvmol". Because "zv" + "mol" = "zvmol". So it's "zvmol". So rotation left 3 of "molzv" gives "zvmol". Wait "molzv" -> left 3: start at index3 'z', then index4 'v', then index0 'm', index1 'o', index2 'l' -> yields "z","v","m","o","l" = "zvm ol"? Actually that's "z","v","m","o","l" which spells "zvm ol"? But "z","v","m","o","l" => "zvm ol"? The correct concatenation is "zvm ol"? No, it's "z","v","m","o","l" -> "zvmo l"? Let's do: 'z' + 'v' = "zv"; then + 'm' = "zvm"; then + 'o' = "zvmo"; then + 'l' = "zvm ol"? Actually "zvmo" + "l" = "zvmo l"? That is 6 characters if there's a space? No, there is no space. The string "zvmo" plus "l" results in "zvmo"+"l" = "zvmo l"? That's "zvmo" followed by 'l' gives "zvm ol"? I think the correct representation is "zvmo l"? I'm going to break out of this. Let's just treat it as a sequence; it's not important for the problem. We'll compute distances.
Better: Let's compute minRotDist for each candidate.
List all rotations of s1 with distances:
s1 = "molzv"
d=0: "molzv"
d=1: take indices 1,2,3,4,0 => o,l,z,v,m => "olzvm"? Actually check: s1: m o l z v. left1: o l z v m -> "olzvm"? That's "olzvm". Yes.
d=2: indices 2,3,4,0,1 => l,z,v,m,o -> "lzvmo"? Actually l,z,v,m,o => "lzvmo". Yes.
d=3: indices 3,4,0,1,2 => z,v,m,o,l -> "zvm ol"? It's "zvm ol"? Let's call it "zvm ol"? But I'll denote as "zvm ol"? Actually it's "zvm ol"? Let's just note as "zvm ol"? Hmm, I think it's "zvmo l"? I'll represent as "zvmo l"? But it's actually "zvmo l"? Let's compute precisely: z + v = "zv"; + m = "zvm"; + o = "zvmo"; + l = "zvm ol"? No, "zvmo"+"l" = "zvm ol"? Actually if I write "zvmo" and then "l", the result is "zvmo"+"l" = "zvm ol"? That yields 5 characters: positions: 1:z,2:v,3:m,4:o,5:l. So the string is "z","v","m","o","l". That is exactly "zvmo l"? But "zvmo l" would have a space between o and l? No. The string is "zvmo l"? Without space: "zvm ol"? I'm not sure.
Maybe I'll write it as "zvmo l"? The answer: It's "zvm ol"? Actually "zvmo"+"l" = "zvm ol"? Let's just write as "zvm ol"? I think the correct string is "zvm ol"? It seems that my brain is inserting a space because "ol" looks like a separate syllable. But there is no space. So I'll treat it as an arbitrary string: rotation3 = "zvm ol"? I'll denote it as s1_rot3.
Anyway, we have candidate rotations. We need to find which one is common with s2.
s2 = "lzvmo". Its rotations:
d=0: "lzvmo"
d=1: left1: indices 1,2,3,4,0 => z,v,m,o,l -> "zvm ol"? That's the same as s1_rot3? Let's see: s1_rot3 is also "z","v","m","o","l"? Actually s1_rot3 = "z","v","m","o","l" which matches s2 left1. So indeed s1_rot3 equals s2 left1. Good.
d=2: left2: indices 2,3,4,0,1 => v,m,o,l,z -> "vmolz"? Actually v,m,o,l,z -> "vmolz".
d=3: left3: indices 3,4,0,1,2 => m,o,l,z,v -> "molzv" (which is s1)
d=4: left4: indices 4,0,1,2,3 => o,l,z,v,m -> "olzvm" (s1_rot1)
So common rotations between s1 and s2 are: s1_rot0="molzv" appears as s2_rot3; s1_rot1="olzvm" appears as s2_rot4; s1_rot2="lzvmo" appears as s2_rot0; s1_rot3 (the "z v m o l") appears as s2_rot1; s1_rot4 = what's s1 left4? Let's compute s1 left4: indices4,0,1,2,3 => v,m,o,l,z? Actually s1: m,o,l,z,v. left4: v,m,o,l,z -> "vm olz"? That's "vmolz"? Yes "vmolz". Does s2 have "vmolz"? s2 left2 is "vmolz". Yes. So all five rotations are common (since both strings are rotations of each other, they have same set). So all five are common.
Now compute total moves for each candidate:
Candidate "molzv" (s1_rot0):
- s1: minRotDist = 0 (since it's the string itself) but careful: s1 is "molzv", so d=0.
- s2: need to get "molzv". s2 rotations: "molzv" is at d=3 (left3). Also maybe d? Only one? So d=3.
Total = 0+3=3.
But sample output says 2. So something off. Let's recalc: Actually the sample output is 2. So maybe we are missing something: The moves count for s2 to become "molzv" might be 2? Let's see: s2 = "lzvmo". To get "molzv", we need to rotate left? Let's check: rotate left by ? Starting "lzvmo". After 1 left: "zvmo l"? Actually "lzvmo" left1 -> "zvmo l"? Actually "lzvmo" left1 = "zvm ol"? Wait we computed earlier: left1 gives "zvm ol"? Actually we computed s2 left1 = "zvm ol"? Let's recompute s2: s2 = "lzvmo". Indices: 0:l,1:z,2:v,3:m,4:o. left1: indices1,2,3,4,0 => z,v,m,o,l => string "zvm ol"? That is "z v m o l" -> "zvm ol"? Actually that's "zvm ol"? Let's call it "zvmo l"? Let's compute: z+v+m+o+l = "zvm ol"? I think it's "zvmo l"? Actually the concatenation gives "zvmo l"? because z+v= "zv", +m = "zvm", +o = "zvmo", +l = "zvm ol"? No, "zvmo"+"l" = "zvm ol"? That's 5 letters: z,v,m,o,l. That string could be written as "zvmo l"? Without space: "zvmo l"? If we write "zvmo l", there is a space. Actually the correct is "zvmo l"? I think it's "zvmo l"? I'm mixing up. Let's just denote it as "zvmo l"? But I'm not comfortable. Let's just compute using Python mental: s2 = "lzvmo". s2[1:]+s2[0] = "zvmo"+"l" = "zvm ol"? Actually "zvmo"+"l" = "zvm ol"? The correct result is "zvmo l"? That is "zvmo" followed by 'l' gives "zvmo l"? Wait "zvmo"+"l" yields a 5-character string: first 4 characters of "zvmo" are z,v,m,o, then append 'l' gives characters: z,v,m,o,l. So the string is "z","v","m","o","l". That is exactly "zvm ol"? The issue is that "zvmo"+"l" naturally yields "zvm ol"? I can't get rid of the phantom space. I'm going to write it as "zvmo l"? Actually if I type "zvmo" and then "l", I get "zvmo l"? That includes a space? No, I'm manually typing. The string is "z v m o l". It is often written as "zvm ol"? But actually, if you write "zvm ol", it has 6 characters: 'z','v','m',' ','o','l'. So that's not. I think the correct string is "zvmo l"? That also has a space. Let's think: The string "zvmo l" would be 'z','v','m','o',' ','l'? Actually "zvmo l" is 6 with space between o and l. So not.
I'll drop this and use actual letters: 'z','v','m','o','l' -> what does that spell when typed consecutively? "zvmo l"? If I type "z v m o l" without spaces, I get "zvm ol"? No, typical concatenation: "z"+"v" = "zv", then add "m" = "zvm", then add "o" = "zvmo", then add "l" = "zvm ol"? That's "zvmo l"? Actually it's "zvmo l"? I realize now: The issue is that "zvmo"+"l" yields "zvmo l"? But there is no space; it's just that "zvmo" ends with 'o', so adding 'l' gives "zvmo l"? Actually, the string is "zvmo l"? That's six characters? Let's just count: "zvmo" is 4 characters: z, v, m, o. Adding 'l' gives 5 characters: z, v, m, o, l. So it's "z v m o l". That can be written as "zvmo l"? But "zvmo l" has a space between o and l? If you write "zvmo l" you might be interpreting as "zvmo" followed by a space then "l"? But I'm not intending a space. The correct representation is "zvmol". Yes, that's it! The string is "zvmol". Because if you concatenate "z"+"v"+"m"+"o"+"l", you get "zvmol". That's a five-letter string: z v m o l. So the word is "zvmol". My earlier confusion: I was reading "zvmo" as a substring, then adding "l" yields "zvmo l"? Actually "zvmo"+"l" = "zvmo l"? No, because "zvmo"+"l" = "zvmo l"? That would be if you typed "zvmo" then "l", you'd get "zvmo l"? But if you type without any separator, you get "zvmol". So it's "zvmol". So s2 left1 = "zvmol". And s1 left3 = "zvmol". Good.
So candidate "molzv": s2 to "molzv": find rotation of s2 that equals "molzv". s2 is "lzvmo". Let's list s2 rotations properly with strings:
s2 = "lzvmo"
d0: lzvmo
d1: zvmo + l = "zvmo"+"l" = "zvmol"? Actually careful: s2[1:] = "zvmo", s2[0] = "l", so d1 = "zvmo"+"l" = "zvmol". So d1 = "zvmol".
d2: s2[2:] + s2[:2] => s2[2:] = "vmo"? Actually indices: 0:l,1:z,2:v,3:m,4:o. s2[2:] = "vmo"? That's "vmo"? Wait s2[2] = v, s2[3] = m, s2[4] = o => "vmo". s2[:2] = "lz". So d2 = "vmo"+"lz" = "vm olz"? That's "vmolz". So d2 = "vmolz".
d3: s2[3:] + s2[:3] => s2[3:] = "mo"? Actually indices 3:m,4:o => "mo". s2[:3] = "lzv". So d3 = "mo"+"lzv" = "molzv". So d3 = "molzv".
d4: s2[4:] + s2[:4] => s2[4:] = "o", s2[:4] = "lzvm" => d4 = "o"+"lzvm" = "olzvm". So d4 = "olzvm".
So indeed "molzv" is at d3. So distance = 3.
But the sample answer is 2. So maybe the optimal target is not "molzv" but something else that yields total 2. Let's compute total for other candidates:
Candidate "olzvm" (s1_rot1):
- s1 distance: d=1 (since "molzv" left1 = "olzvm"? Check: s1 left1 = "olzvm". Yes. So distance 1.
- s2 distance: s2 to "olzvm": s2 has "olzvm" at d4 (as above). So distance 4. Total = 1+4=5.
Candidate "lzvmo" (s1_rot2):
- s1 distance: s1 left2 = "lzvmo" is at d2? Actually s1 left2 = "lzvmo". So d=2.
- s2 distance: s2 itself is "lzvmo", d=0. Total = 2+0=2. That gives total 2. So minimal is 2.
Candidate "zvmol" (s1_rot3):
- s1 distance: d=3? Actually s1 left3 = "zvmol". So d=3.
- s2 distance: s2 left1 = "zvmol", d=1. Total = 3+1=4.
Candidate "vmolz" (s1_rot4):
- s1 distance: d=4.
- s2 distance: s2 left2 = "vmolz", d=2. Total = 6.
So min is 2, matches sample.
So our approach works.
Third sample: all same "kc" -> for candidate "kc" from s1 rotation, distances all 0 -> total 0.
Fourth sample: "aa", "aa", "ab". s1="aa", s2="aa", s3="ab". Rotations of s1: "aa" (d0) and "aa" (d1) both same string. For candidate "aa", check s3: can s3 "ab" be rotated to "aa"? Rotations of "ab": "ab", "ba". Neither is "aa". So no common rotation. So output -1. Good.
Thus algorithm straightforward.
Edge Cases:
-
n=1. Then we can make all strings equal (trivially) with 0 moves, because there is only one string. Our algorithm: For each rotation of s[0], compute total = minRotDist(s[0], candidate). minRotDist(s[0], candidate) for candidate that is rotation of s[0] will be the minimal d. Since we can also choose not to move? Actually we need to make all strings equal; if n=1, any rotation works, but we want minimal moves. The minimal moves is 0 because we can leave it as is (target = s[0] itself). So answer should be 0. Our algorithm will consider candidate rotations, compute total = minRotDist(s[0], candidate). The minimum of these totals will be 0 (for candidate = s[0] itself, minRotDist = 0). So answer 0. Good.
-
Strings may have different lengths? Input says lengths of strings are equal. So fine.
-
Strings may be empty? Not allowed (positive).
Implementation details:
We need a function rotate(s, d) that returns s rotated left by d. But for minRotDist, we need to find smallest d where rotated string equals target. We can just iterate d from 0 to L-1, generate rotated string and compare. Since L ≤ 50, it's fine.
Alternatively, we can precompute for each string a map from rotation string to minimal distance. Because multiple candidates may be same (if string has period). But it's fine.
We should also consider that if the string has period, some rotations produce identical strings. For example, s = "aa". Rotations: d=0 -> "aa", d=1 -> "aa". So candidate "aa" appears for both d=0 and d=1. Our loop over d from 0 to L-1 will consider candidate "aa" twice, but the total computed will be same (since minRotDist(s[0],"aa") = 0, total = sum of others). But we might compute duplicate work, not harmful. However, we might mistakenly think candidate is invalid if we use the exact d? But we use minRotDist for each string, so we will compute correctly regardless. The only issue: if candidate is duplicate, we will compute same total multiple times, but we take min. So fine.
But we must be careful: For s[0] itself, minRotDist(s[0], candidate) might be less than d (the shift used to generate candidate). For example, s[0] = "aa", candidate generated from d=1 gives "aa". minRotDist(s[0], "aa") = 0, not 1. So our algorithm as described (for each d, candidate = rotate(s[0], d), total = minRotDist(s[0], candidate) + sum others) works correctly. That's what we will do.
Thus the algorithm is solid.
Now, potential issues: The strings may have length up to 50, n up to 50. The number of candidates is L (≤50). For each candidate, we check each of n strings (≤50), and for each we try up to L rotations (≤50). So total operations ≤ 505050 = 125,000, which is fine.
Implementation:
Pseudo:
def min_rot_dist(s, target):
L = len(s)
for d in range(L):
if s[d:] + s[:d] == target:
return d
return -1
def solve():
import sys
input_data = sys.stdin.read().splitlines()
n = int(input_data[0].strip())
strings = input_data[1:1+n]
L = len(strings[0])
ans = float('inf')
# For each candidate rotation of first string
for d0 in range(L):
candidate = strings[0][d0:] + strings[0][:d0]
total = 0
valid = True
for s in strings:
dist = min_rot_dist(s, candidate)
if dist == -1:
valid = False
break
total += dist
if valid:
ans = min(ans, total)
if ans == float('inf'):
print(-1)
else:
print(ans)
But careful: The candidate might be duplicate; we could also break early if ans becomes 0 because it can't be lower. But not needed.
Now, verify with examples: Should work.
Consider scenario where there is no solution: return -1.
Edge Cases: Input reading: there may be extra whitespace, but reading splitlines should be fine.
Now, let's think if there's any hidden nuance: The operation is "erase the first character and append it to the end". That is exactly a left rotation. But is there any possibility to achieve a target with fewer moves by doing multiple moves on some strings? Actually the minimal moves to achieve a specific rotation is exactly the minimal left rotation count as we defined. Because any sequence of moves corresponds to left rotating by k moves (where k is number of moves). So to achieve a rotation left by d, you need exactly d moves (if d <= L) or more, but minimal is d mod L. Since we take minimal d from 0..L-1, that's correct.
But there is also possibility of not rotating a string at all (0 moves). So yes.
Thus solution is straightforward.
But before finalizing, consider potential alternative: maybe we could also consider target that is not a rotation of s1 but still can be obtained by rotating all strings? If it's a common rotation, it must be a rotation of each string, thus of s1. So correct.
Hence answer.
Now, we can think about optimizing by precomputing distances: For each string i, for each shift d, compute rotated string and store in a map from string to minimal d. Then for each candidate we can quickly get distance by lookup. But not necessary.
Now, implement.
Testing with sample:
Input 1:
4
xzzwo
zwoxz
zzwox
xzzwo
Our algorithm will compute candidate rotations of s1 (xzzwo):
d0: xzzwo -> total? We computed earlier total 7.
d1: zzwox -> total? 6.
d2: zwoxz -> total? 5.
d3: woxzz -> total? 9.
d4: oxzzw -> total? 13.
Min =5 -> output 5.
Input2:
2
molzv
lzvmo
Our algorithm:
s1 rotations: d0 "molzv": total = minRotDist(s1,"molzv")=0 + minRotDist(s2,"molzv")=3 => 3.
d1 "olzvm": total = 1 + 4 =5.
d2 "lzvmo": total = 2 + 0 =2.
d3 "zvmol": total = 3 + 1 =4.
d4 "vmolz": total = 4 + 2 =6.
min=2 -> output 2.
Input3:
3
kc
kc
kc
-> candidate "kc" d0 total 0+0+0=0, candidate "ck"? Actually s1 = "kc", rotate left1 => "ck". Check s2: "kc" rotate to "ck"? That would be left1? Actually "kc" left1 = "ck". So distance 1. So total = 1+1+1? Actually for candidate "ck": minRotDist(s1,"ck")=1 (since "kc" left1 = "ck"), s2 same 1, s3 same1 total=3. But minimal is 0. So answer 0.
Input4:
3
aa
aa
ab
-> candidate "aa" (d0 and d1 both same) but s3 can't rotate to "aa", so invalid. Thus no valid candidate, ans remains INF -> -1.
All good.
Now, confirm the note: In first sample testcase the optimal scenario is to transform all strings into "zwoxz". That's our candidate d2 for s1.
Thus answer.
We should also consider that maybe we can combine moves in a different way? For example, we could rotate strings multiple times and maybe end up with a different total if we consider that rotating a string also changes it for subsequent comparisons? But we need all strings to equal the same string. The moves are independent per string. So total moves is sum of independent moves for each string. So no interaction.
Thus solution is correct.
Now, complexity wise fine.
Implementation details: We'll need to handle reading lines properly. Could use sys.stdin.readline.
Also note: Strings may contain spaces? No, they consist of lowercase English letters.
Now, final code:
def min_rotations(s, target):
L = len(s)
for d in range(L):
if s[d:] + s[:d] == target:
return d
return -1
def main():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
n = int(data[0])
strings = data[1:1+n]
L = len(strings[0])
INF = 10**9
ans = INF
for d in range(L):
candidate = strings[0][d:] + strings[0][:d]
total = 0
ok = True
for s in strings:
dist = min_rotations(s, candidate)
if dist == -1:
ok = False
break
total += dist
if ok:
ans = min(ans, total)
if ans == INF:
print(-1)
else:
print(ans)
if name == "main":
main()
But careful: using split() will break lines and also split each string? Strings are single words, no spaces. So fine.
Now, ensure we handle the case n=0? Not allowed.
Potential improvements: early exit if ans == 0.
Now, let's test some extra cases:
Case: n=2, s1="ab", s2="ab". Rotations: both same. candidate "ab": total 0, candidate "ba": total 1+1=2. So answer 0.
Case: n=2, s1="ab", s2="ba". Rotations: both have each other. candidate "ab": total 0+1=1, candidate "ba": total 1+0=1. So answer 1. Let's simulate: we can rotate s2 by 1 to get "ab", total moves 1. Or rotate s1 by 1 to get "ba", total 1. So 1. Our algorithm: For candidate "ab" (d0) total = minRotDist(s1,"ab")=0 + minRotDist(s2,"ab")=1 =1. For "ba" (d1) total = 1+0=1. So min 1. Good.
Case: strings with period: s1="aaa", s2="aaa". Rotations all "aaa". candidate "aaa": total 0. So answer 0.
Case: s1="abc", s2="bca", s3="cab". All rotations of each other. Compute candidate rotations of s1:
- "abc": s1=0, s2: "bca" to "abc"? need rotation left? "bca" left? "bca" left1="cab", left2="abc"? Actually "bca" left2 = "abc"? Let's compute: "bca": indices 0:b,1:c,2:a. left2: indices2:a + indices0:b + indices1:c => "abc". So distance 2. s3: "cab" left? to "abc": "cab" left1="abc"? Actually "cab" left1 = "abc"? "cab": left1: "ab"+"c"? Wait "cab": indices1:a, indices2:b, indices0:c => "abc". So distance 1. Total = 0+2+1=3.
- "bca": s1: distance 1? "abc" left1 = "bca" -> 1; s2: distance 0; s3: "cab" to "bca": "cab" left2 = "bca"? "cab" left2: indices2:b? Actually "cab": indices2=b, indices0=c, indices1=a => "bca"? Wait "cab": indices0=c,1=a,2=b. left2: start index2 = b, then index0=c, then index1=a => "bca". So distance 2. total =1+0+2=3.
- "cab": s1: distance 2; s2: distance 1; s3: 0; total=3. So answer 3. That seems plausible.
Could there be a target that is not a rotation but maybe we can rotate each string different amounts to converge to same string? That's exactly what we did.
Thus answer is sum of distances to target.
Thus solution correct.
Now, perhaps there is an alternative approach using string matching and distance computation via KMP or similar, but not needed.
Now, consider possibility of using BFS? No.
So final answer is as above.
But before finalizing, check constraints: n up to 50, length up to 50. So our approach is fine.
One subtlety: The operation is "erase the first character and append it to the end". It is a left rotation. But if we rotate left d times, we get the same as rotating right (L-d) times. However, we cannot rotate right directly, but we could rotate left (L-d) times to achieve the effect of a right rotation but it would be more moves than left d? Actually if we want to achieve a rotation that is effectively a right rotation by r, we could rotate left by L-r moves, which is more than r if r < L/2? But we are allowed only left rotations, so we must consider minimal left rotations. So the distance we compute is the minimal number of left rotations that yields the target. That's correct.
But could there be a case where we can achieve a target by a combination of moves on different strings that interact? No.
Thus final answer.
Now, we can produce final response with explanation and code.
But the problem statement: "Print the minimal number of moves Mike needs in order to make all the strings equal or print - 1 if there is no solution." So we need to output an integer.
Edge Cases: If some string is already equal to some rotation, but we might rotate it anyway; we want minimal total moves.
Now, implementation details in Python: In min_rot_dist, we could also use (s+s).find(target) to find the first occurrence, but careful: find returns index of first occurrence; if target appears, that index is the left rotation count? Actually if we concatenate s with itself, then find(target) returns the starting index of the first occurrence of target in s+s, which if target is a rotation, the index is the number of left shifts needed to get target (provided we check only indices from 0 to L-1). But careful: If s has periodic structure, find may return a smaller index than the minimal d? Actually if target appears multiple times, find returns the first index. That index will be the minimal d? For example, s="aa", target="aa". s+s = "aaaa". find("aa") returns 0, which is minimal d 0. So that works. But we need to ensure that the found index is less than L. Since we only consider rotations up to L-1, it's fine. But we should also ensure that target length equals L, and that it's a substring of s+s. If it is, the index is the rotation count. However, we also need to verify that the target is indeed a rotation (i.e., length L and appears in s+s). But we can just use that method: if target in s+s and len(target)==len(s) (but if lengths equal, it's fine). But we need the minimal d; using find returns the first occurrence, which is the smallest rotation count that yields target. That could be faster but not necessary.
But we need to handle case where target is not a rotation: then target not in s+s (or appears at index beyond L? Actually if target equals s, it's at index 0; if it's a rotation, it appears at some index < L; if not, it won't appear. So we can test if target in s+s and index < L. But careful: For string of length L, s+s contains all rotations as substrings of length L starting at indices 0..L-1. So if target appears in s+s, then there is some rotation; the first occurrence index gives minimal rotation count. However, if the string has period, there might be multiple indices; the first is minimal. So we can implement min_rot_dist using:
def min_rot_dist(s, target):
if len(s) != len(target):
return -1
double = s + s
idx = double.find(target)
if idx == -1 or idx >= len(s):
return -1
return idx
But careful: double.find(target) may return an index > L-1 if target appears later due to overlapping? Actually for length L, the substrings of length L in double are at indices 0..L. Actually double length is 2L, so indices 0..L inclusive? For L=5, double length 10, substrings of length 5 at indices 0..5. If target appears at index L, that corresponds to substring double[L:L+L] = s[L:] + s[:L] but since s length L, s[L:] is empty, then s[:L] is s, so index L yields the original string again? Actually double = s + s; index L gives the second copy of s starting at position L. That substring is s again. So if target == s, it may appear at index L as well as 0. find returns the smallest index, which is 0. So it's fine. But could target appear at index > L? The maximum starting index for a length L substring in a string of length 2L is L, because after that the substring would go beyond length? Actually last index is L (since indices L to L+L-1 is the second half). So find will only return indices between 0 and L inclusive. If it returns L, that means target equals s and the first occurrence was at L? But that would happen only if s doesn't appear earlier, but s appears at 0 always. So it would return 0, not L. So we don't need to worry.
Thus we can use this method.
But we need to ensure that the target is exactly of length L; it is.
Simpler: use loop; it's fine.
Now, about input reading: Use sys.stdin.read().split() will split by whitespace and give list. First element is n, then n strings. Works.
Now, final code.
We'll produce a final answer with explanation and code.
But the user asked: "Mike has n strings ... Print the minimal number of moves ... or -1 if no solution." So they want code.
In typical problems, we need to output answer.
I'll produce the solution in Python.
Also, note that the problem could be solved with C++ as well, but here Python is fine.
Thus final.
But I'd like to consider an edge case: The strings may have length 1. Then there is only one rotation (the string itself). So either they are all same (answer 0) or not (-1). Our algorithm: L=1, d0 only. candidate = s[0][0:] + s[0][:0] = s[0]. Then for each s, minRotDist(s, candidate). For s[0] itself, d=0. For others, if s equals candidate, d=0; else no rotation (since only rotation is itself, but if not equal, minRotDist returns -1). So works.
Now, confirm with n=1 length 1: answer 0.
Now, consider strings with length 2, but periodic like "aa". Works.
Thus final.
Implementation:
We'll provide final code.
But we must consider time: For each candidate we call min_rot_dist for each string, which loops up to L. That's okay.
Now, we can also implement early exit if ans == 0 (since can't be lower) but not necessary.
Now, final answer.
I'll write a clear explanation in the response: outline the approach, then code.
Now, produce final. ```python
import sys
def min_rotations(s: str, target: str) -> int:
"""
Returns the smallest number of left rotations needed to turn s into target.
If target is not a rotation of s, returns -1.
"""
L = len(s)
# try all rotation amounts
for d in range(L):
if s[d:] + s[:d] == target:
return d
return -1
def main() -> None:
data = sys.stdin.read().split()
if not data:
return
n = int(data[0])
strings = data[1:1+n]
L = len(strings[0])
INF = 10**9
answer = INF
# try every rotation of the first string as candidate
for d in range(L):
candidate = strings[0][d:] + strings[0][:d]
total = 0
possible = True
for s in strings:
dist = min_rotations(s, candidate)
if dist == -1:
possible = False
break
total += dist
if possible:
answer = min(answer, total)
if answer == INF:
print(-1)
else:
print(answer)
if name == "main":
main()