Given a string, check if it is a rotated palindrome or not.

For example,

CBAABCD is a rotated palindrome as it is a rotation of palindrome ABCDCBA.
BAABCC is a rotated palindrome as it is a rotation of palindrome ABCCBA.

Practice this problem

Approach 1

A naive solution is to consider all rotations of the given string and check if any rotation is a palindrome or not. If we have found a rotation that is a palindrome, return true; otherwise, return false.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The string is a rotated palindrome

Java


Download  Run Code

Output:

The string is a rotated palindrome

Python


Download  Run Code

Output:

The string is a rotated palindrome

Approach 2

The problem is similar to finding the Longest Palindromic Substring problem. Let the given string be S of length n. The idea is to concatenate the string with itself, i.e., (S = S + S), and find a palindromic substring of length n in the modified string (S + S). If a palindromic substring of length n exists in the modified string, return true; otherwise, return false.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The string is a rotated palindrome

Java


Download  Run Code

Output:

The string is a rotated palindrome

Python


Download  Run Code

Output:

The string is a rotated palindrome

The time complexity of both above-discussed methods is O(n2), where n is the length of the input string and doesn’t require any extra space.