Given a string str, the task is to find the number of strings that start and end with the same character after a rotation at every possible index of the given string.
Input: str = “GeeksforGeeks”
All possible strings with rotations at every index are: “GeeksforGeeks”, “eeksforGeeksG”, “eksforGeeksGe”, “ksforGeeksGee”, “sforGeeksGeek”, “forGeeksGeeks”, “orGeeksGeeksf”, “rGeeksGeeksfo”, “GeeksGeeksfor”, “eeksGeeksforG”, “eksGeeksforGe”, “ksGeeksforGee”, “sGeeksforGeek”.
Out of the above strings formed only 2 string starts and ends with the same characters: “eksforGeeksGe” and “eksGeeksforGe”.
Input: str = “aaabcdd”
All possible strings with rotations at every index are: “aaabcdd”, “aabcdda”, “abcddaa”, “bcddaaa”, “cddaaab”, “ddaaabc”, “daaabcd”.
Out of the above strings formed only 3 string starts and ends with the same characters: “aabcdda”, “abcddaa” and “daaabcd”.
Naive Approach: The idea is to generate all the possible rotations of the given string and check whether the each string formed after rotation starts and ends with the same character or not. If Yes then include this string in the count. Print the final count.
Efficient Approach: The efficient approach to counting the possible string is to rotate the given string at those indexes which have continuous same characters. Therefore, the final count is the (number of continuous same characters – 1) for each continuous characters in the given string.
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of the given string.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live