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.

C++ implementation –

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.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂