Mike and Strings

Practice this coding question on Coding Gurukul.

Problem statement

Mike maintains circular text displays mounted with different starting positions. One button press on a display moves its first character to the end. He wants every display to show exactly the same string, while using the smallest total number of button presses across all displays. Your task Find the minimum total number of left cyclic shifts needed to make all supplied strings identical. Print -1 if it is impossible. Important details All strings have equal length. You may shift each string a different number of times, and a string already at the chosen target needs zero shifts. Repeated characters can create several equivalent rotation amounts; count the cheapest. Only rotation is allowed, not arbitrary rearrangement. Worked example For abc, bca and cab, choosing abc costs 0, 2 and 1 left shifts, totaling 3. Choosing either other rotation also costs 3, so the answer is 3. The strings ab and ac cannot become identical through rotations and produce -1.

Input format

Read n, then n lowercase strings, one per line.

Output format

Print the minimum total shifts, or -1.

Constraints

1 <= n <= 50; all strings have the same length between 1 and 50; lowercase English letters only.

Sample input

3
abc
bca
cab

Sample output

3

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…