The lexicographically minimal string rotation (or lexicographically least circular substring) is the problem of finding a string’s rotation possessing the lowest lexicographical order among all possible rotations.

For example, the lexicographically minimal rotation of bbaaccaadd is aaccaaddbb. A string can have multiple lexicographically minimal rotations, but this doesn’t matter – rotations must be equivalent.

Practice this problem

 
The idea is to iterate through successive rotations of the given string while keeping track of the most lexicographically minimal rotation encountered. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The lexicographically minimal rotation of bbaaccaadd is aaccaaddbb

Java


Download  Run Code

Output:

The lexicographically minimal rotation of bbaaccaadd is aaccaaddbb

Python


Download  Run Code

Output:

The lexicographically minimal rotation of bbaaccaadd is aaccaaddbb

The time complexity of the above solution is O(n2), where n is the length of the input string and doesn’t require any extra space.

 
Booth’s algorithm can solve this problem in O(n) time. The algorithm uses a modified preprocessing function from the Knuth–Morris–Pratt string searching algorithm. The failure function for the string is computed as normal, but the string is rotated during the computation, so some indices must be computed more than once as they wrap around. Once all indices of the failure function have been successfully computed without the string rotating again, the minimal lexicographical rotation is known to be found, and its starting index is returned.