Find Lexicographically minimal string rotation

Lexicographically minimal string rotation or lexicographically least circular substring is the problem of finding the rotation of a string possessing the lowest lexicographical order of all such rotations.


For example, the lexicographically minimal rotation of bbaaccaadd would be aaccaaddbb. It is possible for a string to have multiple lexicographically minimal rotations, but this does not matter as the rotations must be equivalent.

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


Download   Run Code


Download   Run Code


The lexicographically minimal rotation of bbaaccaadd is aaccaaddbb


The time complexity of above solution is O(n2) and auxiliary space used by the program is O(1).

Booth’s Algorithm can solve this problem in O(n) time. The algorithm uses a modified preprocessing function from the Knuth-Morris-Pratt string search 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. We will be soon discussing implementation of Booth’s Algorithm.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of