Given a string, check if it is a rotation of a palindrome. For example your function should return true for “aab” as it is a rotation of “aba”.
Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any palindrome.
We strongly recommend that you click here and practice it, before moving on to the solution.
A Simple Solution is to take the input string, try every possible rotation of it and return true if a rotation is a palindrome. If no rotation is palindrome, then return false.
Following is the implementation of this approach.
1 0 1
Time Complexity: O(n2)
Auxiliary Space: O(n) for storing rotations.
Note that the above algorithm can be optimized to work in O(1) extra space as we can rotate a string in O(n) time and O(1) extra space.
An Optimized Solution can work in O(n) time. The idea is similar to this post. Following are steps.
1) Let the given string be ‘str’ and length of string be ‘n’. Create a temporary string ‘temp’ which is of size 2n and contains str followed by str again. For example, let str be “aab”, temp would be “aabaab”.
2) Now the problem reduces to find a palindromic substring of length n in str. If there is palindromic substring of length n, then return true, else return false.
We can find whether there is a palindromic substring of size n or not in O(n) time (See Longest palindromic substring)
This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Check if a string is palindrome in C using pointers
- Check if it is possible to create a palindrome string from given N
- Check if any anagram of a string is palindrome or not
- C Program to Check if a Given String is Palindrome
- Left Rotation and Right Rotation of a String
- Python program to check if a string is palindrome or not
- Check if there exists any sub-sequence in a string which is not palindrome
- Recursive function to check if a string is palindrome
- Given two strings check which string makes a palindrome first
- Python program to check if given string is vowel Palindrome
- Check if characters of a given string can be rearranged to form a palindrome
- Check if a string can be rearranged to form special palindrome
- Check if the characters in a string form a Palindrome in O(1) extra space
- Lexicographically minimum string rotation | Set 1
- Convert the string into palindrome string by changing only one character.
Improved By : shrikanth13