![]() |
VOOZH | about |
A rotation of a string can be generated by moving characters one after another from beginning to end. For example, the rotations of acab are acab, caba, abac, and baca.
Your task is to determine the lexicographically minimal rotation of a string.
Examples:
Input: s = "acab"
Output: abac
Explanation: All possible rotations are: "acab", "caba", "abac" and "baca". The lexicographically smallest string is "abac".Input: s = "GeeksforGeeks"
Output: GeeksGeeksfor
Explanation: Out of possible rotations "GeeksGeeksfor" is lexicographically smallest.
Approach: To solve the problem, follow the below idea:
The idea is to uses Booth’s algorithm, which is a well-known algorithm for this problem. The main idea of Booth’s algorithm is to construct a failure function (similar to the one used in the KMPpattern matching algorithm) for the given string concatenated with itself. This failure function is used to efficiently compare prefixes of the string to find the smallest rotation.
Let's break our idea in some steps:
- Concatenate the string to itself: This allows us to easily handle the wrap-around nature of rotations without having to use modular arithmetic.
- Initialize the failure function and the minimum rotation index: The failure function f is an array that stores the length of the longest proper suffix of the substring S[0..j] which is also a proper prefix of S. The minimum rotation index k keeps track of the starting index of the smallest rotation found so far.
- Iterate over the concatenated string: For each character S[j] in the string, we compare it with the character at the corresponding position in the current smallest rotation. If S[j] is smaller, we update the minimum rotation index k.
- Update the failure function: The failure function is updated based on whether S[j] is equal to S[k + f[j - k - 1] + 1] . If they are equal, f[j - k] is set to f[j - k - 1] + 1. Otherwise, f[j - k] is set to -1.
- Return the minimum rotation index: After iterating over the entire string, the minimum rotation index k gives the starting index of the lexicographically smallest rotation.
Step-by-step algorithm:
Below is the implementation of the algorithm:
abac
Time Complexity: O(n), where n is the length of the input string s.
Auxiliary Space: O(n), where n is the length of the input string s.