Python3 Program to Find Lexicographically smallest rotated sequence | Set 2
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD
Input Constraint: 1 < n < 1000Â
Examples:Â
Â
Input: GEEKSQUIZ
Output: EEKSQUIZG
Input: GFG
Output: FGG
Input : CAPABCQ
Output : ABCQCAP
Â
We have discussed a O(n2Logn) solution in Lexicographically minimum string rotation | Set 1. Here we need to find the starting index of minimum rotation and then print the rotation.
Â
1) Initially assume 0 to be current min
starting index.
2) Loop through i = 1 to n-1.
a) For each i compare sequence starting
at i with current min starting index
b) If sequence starting at i is lexicographically
smaller, update current min starting
index.
Here is pseudo-code for algorithmÂ
Â
function findIndexForSmallestSequence(S, n):
result = 0
for i = 1:n-1
if (sequence beginning at i <
sequence beginning at result)
result = i
end if
end for
return result
Here is implementation of above algorithm.Â
Â
Python 3
import copy
def printSmallestSequence(s):
m = copy.copy(s)
for i in range ( len (s) - 1 ):
if m > s[i:] + s[:i]:
m = s[i:] + s[:i]
return m
if __name__ = = '__main__' :
st = 'DCACBCAA'
print (printSmallestSequence(st))
|
Output:Â
Â
AADCACBC
Time Complexity : O(n^2)Â
Auxiliary Space : O(1)
Please refer complete article on Lexicographically smallest rotated sequence | Set 2 for more details!
Last Updated :
10 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...