Given a string, we need to find the minimum number of rotations required to get the same string. In this case, we will only consider Left rotations.
Input : s = “geeks”
Output : 5
Input : s = “aaaa”
Naive approach: The basic approach is to keep rotating the string from the first position and count the number of rotations until we get the initial string.
Efficient Approach : We will follow the basic approach but will try to reduce the time taken in generating rotations.
The idea is as follows:
- Generate a new string of double size of the input string as:
newString = original string excluding first character + original string with the first character. + denotes concatenation here.
If orginal string is str = “abcd”, new string will be “bcdabcd”.
- Now, the task remains to search for the original string in the newly generated string and the index where the string is found in the number of rotations required.
- For string matching, we will use KMP algorithm which performs string matching in linear time.
Below is the implementation of the above approach:
Time Complexity : O(N).
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.
- Minimum rotations required to get the same string
- Number of strings which starts and ends with same character after rotations
- Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings
- Minimum number of pairs required to make two strings same
- Generate all rotations of a given string
- Rotations of a Binary String with Odd Value
- Maximum contiguous 1 possible in a binary string after k rotations
- Minimum changes required to make first string substring of second string
- Minimum number of given operations required to convert a string to another string
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Minimize the number of replacements to get a string with same number of 'a', 'b' and 'c' in it
- A Program to check if strings are rotations of each other or not
- Check if all rows of a matrix are circular rotations of each other
- Count rotations divisible by 4
- Check if strings are rotations of each other or not | Set 2
- Minimum swaps required to convert one binary string to another
- Minimum swaps required to make a binary string alternating
- Minimum changes required such that the string satisfies the given condition
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum given operations required to convert a given binary string to all 1's
Improved By : divyamohan123