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
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.
Following is the implementation of above solution.
EEKSFORGEEKSG EEKSQUIZG ABBCABDAD
Time complexity of the above solution is O(n2Logn) under the assumption that we have used a O(nLogn) sorting algorithm.
This problem can be solved using more efficient methods like Booth’s Algorithm which solves the problem in O(n) time. We will soon be covering these methods as separate posts.
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Left Rotation and Right Rotation of a String
- Minimum number of flips with rotation to make binary string alternating
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Minimum length of substring whose rotation generates a palindromic substring
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest and largest anagrams of a string containing another string as its substring
- Lexicographically smallest permutation of a string that contains all substrings of another string
- Check if a given string is a rotation of a palindrome
- Queries for rotation and Kth character of the given string in constant time
- Minimize characters to be changed to make the left and right rotation of a string same
- Find n-th lexicographically permutation of a string | Set 2
- Lexicographically next greater string using same character set
- Lexicographically smallest permutation with distinct elements using minimum replacements
- Lexicographically first palindromic string
- Lexicographically n-th permutation of a string
- Find a string such that every character is lexicographically greater than its immediate next character
- Lexicographically first alternate vowel and consonant string
- Lexicographically next string