Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Javascript Program to Find Lexicographically minimum string rotation | Set 1

  • Last Updated : 27 Dec, 2021

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:  GFG
Output: FGG


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. 


// A simple Javascript program to find 
// lexicographically minimum rotation
// of a given String
// This functionr return lexicographically 
// minimum rotation of str
function minLexRotation(str) 
    // Find length of given String
    let n = str.length;
    // Create an array of strings 
    // to store all rotations
    let arr = new Array(n);
    // Create a concatenation of 
    // String with itself
    let concat = str + str;
    // One by one store all rotations 
    // of str in array. A rotation is 
    // obtained by getting a substring of concat
    for(let i = 0; i < n; i++)
        arr[i] = concat.substring(i, i + n);
    // Sort all rotations
    // Return the first rotation 
    // from the sorted array
    return arr[0];
// Driver code
document.write(minLexRotation("GEEKSFORGEEKS") + "</br>");
document.write(minLexRotation("GEEKSQUIZ") + "</br>");
document.write(minLexRotation("BCABDADAB") + "</br>");
// This code is contributed by divyeshrabadiya07



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!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!