Python3 Program to Find Lexicographically minimum string rotation | Set 1
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].
Following is the implementation of above solution.Â
Python3
def minLexRotation(str_) :
n = len (str_)
arr = [ 0 ] * n
concat = str_ + str_
for i in range (n) :
arr[i] = concat[i : n + i]
arr.sort()
return arr[ 0 ]
print (minLexRotation( "GEEKSFORGEEKS" ))
print (minLexRotation( "GEEKSQUIZ" ))
print (minLexRotation( "BCABDADAB" ))
|
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.Â
Please refer complete article on Lexicographically minimum string rotation | Set 1 for more details!
Last Updated :
27 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...