Lexicographically minimum string rotation

Let us consider a string is given, we know that the string is a sequence of characters. The Lexicographical rotation is the rotation of string, to convert characters in lexicographical order.

The solution is simple, we simply concatenate the given string with itself, then in another array, all rotation of strings are stored. After that sort the array in ascending order, the lowest value is the final result.

Input and Output

Input:
The String “BCAAFAABCD”
Output:
Rotated String: “AABCDBCAAF”

Algorithm

minStrRotation(str)

Input − The given string.

Output − Minimum string rotation required.

Begin
   n := length of str
   define strArr to store all rotations
   tempStr := concatenate str with str again

   for i := 0 to n, do
      strArr[i] := substring of tempStr from (i to n)
   done

   sort the strArr
   return strArr[0]
End

Example

#include 
#include 
using namespace std;

string minStrRotation(string str) {
   int n = str.size();
   string strArray[n];    //array to store all rotations of str
   string tempStr = str + str;    //concatinate str two times

   for (int i = 0; i > str;
   cout 

Output

Enter String: BCAAFAABCD
Rotated String: AABCDBCAAF
Updated on: 2020-06-17T10:03:27+05:30

763 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements