Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.

Source: Google Written Test

More Examples:

Input:  GEEKSQUIZ
Output: EEKSQUIZG

Input:  GFG
Output: FGG

Input:  GEEKSFORGEEKS
Output: EEKSFORGEEKSG

Following is a simple solution. Let the given string be ‘str’
1) Concatenate ‘str’ with itself and store in a temporary string say ‘concat’.
2) Create an array of strings to store all rotations of ‘str’. Let the array be ‘arr’.
3) Find all rotations of ‘str’ by taking substrings of ‘concat’ at index 0, 1, 2..n-1. Store these rotations in arr[] 4) Sort arr[] and return arr[0].

[ad type=”banner”]

Following is C++ implementation of above solution.

[pastacode lang=”cpp” manual=”%2F%2F%20A%20simple%20C%2B%2B%20program%20to%20find%20lexicographically%20minimum%20rotation%0A%2F%2F%20of%20a%20given%20string%0A%23include%20%3Ciostream%3E%0A%23include%20%3Calgorithm%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F%2F%20This%20functionr%20return%20lexicographically%20minimum%0A%2F%2F%20rotation%20of%20str%0Astring%20minLexRotation(string%20str)%0A%7B%0A%20%20%20%20%2F%2F%20Find%20length%20of%20given%20string%0A%20%20%20%20int%20n%20%3D%20str.length()%3B%0A%20%0A%20%20%20%20%2F%2F%20Create%20an%20array%20of%20strings%20to%20store%20all%20rotations%0A%20%20%20%20string%20arr%5Bn%5D%3B%0A%20%0A%20%20%20%20%2F%2F%20Create%20a%20concatenation%20of%20string%20with%20itself%0A%20%20%20%20string%20concat%20%3D%20str%20%2B%20str%3B%0A%20%0A%20%20%20%20%2F%2F%20One%20by%20one%20store%20all%20rotations%20of%20str%20in%20array.%0A%20%20%20%20%2F%2F%20A%20rotation%20is%20obtained%20by%20getting%20a%20substring%20of%20concat%0A%20%20%20%20for%20(int%20i%20%3D%200%3B%20i%20%3C%20n%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20%20arr%5Bi%5D%20%3D%20concat.substr(i%2C%20n)%3B%0A%20%0A%20%20%20%20%2F%2F%20Sort%20all%20rotations%0A%20%20%20%20sort(arr%2C%20arr%2Bn)%3B%0A%20%0A%20%20%20%20%2F%2F%20Return%20the%20first%20rotation%20from%20the%20sorted%20array%0A%20%20%20%20return%20arr%5B0%5D%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20cout%20%3C%3C%20minLexRotation(%22GEEKSFORGEEKS%22)%20%3C%3C%20endl%3B%0A%20%20%20%20cout%20%3C%3C%20minLexRotation(%22GEEKSQUIZ%22)%20%3C%3C%20endl%3B%0A%20%20%20%20cout%20%3C%3C%20minLexRotation(%22BCABDADAB%22)%20%3C%3C%20endl%3B%0A%7D” message=”C++ Program” highlight=”” provider=”manual”/]

Output:

EEKSFORGEEKSG
EEKSQUIZG
ABBCABDAD

Time complexity of the above solution is O(n2Logn) under the assumption that we have used a O(nLogn) sorting algorithm.

This problem can be solved using more efficient methods like Booth’s Algorithm which solves the problem in O(n) time. We will soon be covering these methods as separate posts.

[ad type=”banner”]