![]() |
VOOZH | about |
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.
Examples:
Input: n = 2, arr[] = {"molzv", "lzvmo"}
Output: 2
Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second character of first string and move it to end. So after 2 operations, both strings become same.Input: n = 3, arr[] = {"kc", "kc", "kc"}
Output: 0
Explanation: already all strings are equal.
Approach:
The move to end operation is basically left rotation. We use the approach discussed in check if strings are rotations of each other or not to count a number of move to front operations required to make two strings the same. We one by one consider every string as the target string. We count rotations required to make all other strings the same as the current target and finally return a minimum of all counts.
Below is the implementation of the above approach.
5
Time Complexity: O(n3), Where n is the size of given string (n2 for the two nested for loops and n is for the function used as find())
Auxiliary Space: O(n)
To efficiently determine the minimum number of moves required to make all strings in an array identical by rotating characters, we can use the KMP algorithm. This approach leverages the ability of the KMP algorithm to find substring matches efficiently, which helps in quickly determining how many rotations are needed to transform one string into another.
This method revolves around using KMP for pattern searching, which allows us to detect the smallest shift needed for one string to become another. Instead of performing a find operation on concatenated strings (which is computationally expensive), we preprocess the target string to create a partial match table (or pi table). Using this table, we can efficiently determine how many rotations are needed to align one string to another. This reduces the number of operations significantly compared to the naive method.
- Preprocess all Strings: Compute the KMP tables for all strings in advance. This allows us to quickly compare any string against another using the KMP search method.
- Compute Rotations for Each Target: For each string considered as the potential final form, compute how many rotations are required for all other strings to match this target.
- Select Minimum Rotations: Track and return the minimum number of rotations across all potential target strings.
Below is the implementation of the above approach:
5
Time Complexity: O(n^2×m), where m is the length of the longest string.
Auxiliary Space: O(m)