Number of strings which starts and ends with same character after rotations
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 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 character 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.