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 <iostream>
#include <algorithm>
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 < n; i++)
      strArray[i] = tempStr.substr(i, n);    //get sub string from ith index to nth index
   sort(strArray, strArray+n);
   return strArray[0];    //The first index is the result
}

int main() {
   string str;
   cout << "Enter String: "; cin >> str;
   cout << "Rotated String: " << minStrRotation(str);
}

Output

Enter String: BCAAFAABCD
Rotated String: AABCDBCAAF

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 17-Jun-2020

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements