JavaScript Program to Check if a Given String is a Rotation of a Palindrome
Last Updated :
18 Jul, 2024
In this article, we will see how to check a given string is a rotation of a palindrome. A palindrome is a string that remains the same when its characters are reversed (e.g., "racecar" is a palindrome).
Example:
Input: str = "racecar"
Output: true
// "racecar" is a rotation of a palindrome "racecar"
Input: str = "abbab"
Output: true
// "abbab" is a rotation of "abbba".
Input: str = "baba"
Output: true
// "baba" is a rotation of a palindrome "baba".
Input: str = "abcd"
Output: false
// "abcd" is not a rotation of any palimdrome.
Naive Approach
In this approach, we generate all possible rotations of the string and check if any of them is a palindrome. It does this by generating all possible rotations of the string and checking if any of these rotations are palindromes using the isPalindrome function. If it finds a palindrome rotation, it returns true; otherwise, it returns false.
Example: Below is the implementation of the above example.
JavaScript
function isPalindrome(str) {
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
function isRotationOfPalindrome(str) {
if (!str || str.length <= 1) {
return false;
}
const len = str.length;
// Generate all possible rotations
for (let i = 0; i < len; i++) {
const rotated =
str.slice(i) + str.slice(0, i);
// Check if the original string is a palindrome
if (isPalindrome(rotated)) {
return true;
}
}
return false;
}
const inputString = "abcd";
const isRotatedPalindrome =
isRotationOfPalindrome(inputString);
console.log(isRotatedPalindrome);
Time Complexity: O(N^2), where N is the length of the input string
Auxiliary Space: O(N)
Efficient Approach:
In this approach, we will find a specific rotation that makes it easier to determine if the string is a rotation of a palindrome. The code checks if a given string is a rotation of a palindrome. It creates a doubled version of the input string to handle all possible rotations efficiently. Then, it iterates through the doubled string, extracting substrings of the same length as the original string and checking if any of these substrings are palindromes using the isPalindrome function. If it finds a palindrome rotation, it returns true, otherwise, it returns false.
Example: Below is the implementation of the above example.
JavaScript
function isRotationOfPalindrome(str) {
if (!str || str.length <= 1) {
return false;
}
const len = str.length;
// Create a doubled string to handle
// all rotations
const doubledStr = str + str;
// Iterate through the string length
for (let i = 0; i < len; i++) {
const possibleRotation =
doubledStr.slice(i, i + len);
// Check if the possible
// rotation is a palindrome
if (isPalindrome(possibleRotation)) {
return true;
}
}
return false;
}
function isPalindrome(str) {
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
const inputString = 'abba';
const isRotatedPalindrome =
isRotationOfPalindrome(inputString);
console.log(isRotatedPalindrome);
Time Complexity: O(N), where N is the length of the input string
Auxiliary Space: O(N)
Using Hashing
Using hashing, the approach compares the original string's hash with the hashes of all its rotations. If any rotation's hash matches, it verifies if the substring is a palindrome, determining if the string is a rotation of a palindrome.
Example:
JavaScript
function isRotationOfPalindrome(str) {
function isPalindrome(s) {
return s === s.split('').reverse().join('');
}
function computeHash(s) {
let hash = 0;
for (let i = 0; i < s.length; i++) {
hash = (hash * 31 + s.charCodeAt(i)) % (1e9 + 7);
}
return hash;
}
let originalHash = computeHash(str);
let n = str.length;
let power = 1;
let currentHash = 0;
for (let i = 0; i < n; i++) {
currentHash = (currentHash * 31 + str.charCodeAt(i)) % (1e9 + 7);
if (i < n - 1) {
power = (power * 31) % (1e9 + 7);
}
}
for (let i = 0; i < n; i++) {
if (currentHash === originalHash && isPalindrome(str.slice(i) + str.slice(0, i))) {
return true;
}
currentHash = (currentHash - (str.charCodeAt(i) * power) % (1e9 + 7) + (1e9 + 7)) % (1e9 + 7);
currentHash = (currentHash * 31 + str.charCodeAt((i + n) % n)) % (1e9 + 7);
}
return false;
}
console.log(isRotationOfPalindrome("abcd")); // false
console.log(isRotationOfPalindrome("aab")); // true
Using Character Frequency Count
In this approach, we'll determine if the given string can be rearranged into a palindrome. If it can, then it must be a rotation of some palindrome. This is based on the fact that a string that can be rearranged into a palindrome must have at most one character with an odd frequency.
Example:
JavaScript
function canFormPalindrome(str) {
const charCount = new Map();
// Count the frequency of each character
for (let char of str) {
if (charCount.has(char)) {
charCount.set(char, charCount.get(char) + 1);
} else {
charCount.set(char, 1);
}
}
// Check the number of characters with odd frequency
let oddCount = 0;
for (let count of charCount.values()) {
if (count % 2 !== 0) {
oddCount++;
}
}
// For a string to be rearranged into a palindrome,
// there can be at most one character with an odd frequency
return oddCount <= 1;
}
function isRotationOfPalindrome(str) {
// If the string can form a palindrome, then
// it must be a rotation of some palindrome
return canFormPalindrome(str);
}
// Test cases
console.log(isRotationOfPalindrome("racecar"));
console.log(isRotationOfPalindrome("abbab"));
console.log(isRotationOfPalindrome("baba"));
console.log(isRotationOfPalindrome("abcd"));
console.log(isRotationOfPalindrome("aab"));
Outputtrue
true
true
false
true
Approach: Using String Concatenation and Palindrome Check
In this approach, we will leverage the property that a string that is a rotation of a palindrome will be a substring of its doubled version. By concatenating the string with itself, we can efficiently check for all possible rotations.
Example:
JavaScript
function isPalindrome(str) {
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
function isRotationOfPalindrome(str) {
const len = str.length;
const doubledStr = str + str;
for (let i = 0; i < len; i++) {
const substring = doubledStr.substring(i, i + len);
if (isPalindrome(substring)) {
return true;
}
}
return false;
}
// Example usage:
const inputStr1 = "racecar";
const inputStr2 = "abbab";
const inputStr3 = "baba";
const inputStr4 = "abcd";
console.log(isRotationOfPalindrome(inputStr1));
console.log(isRotationOfPalindrome(inputStr2));
console.log(isRotationOfPalindrome(inputStr3));
console.log(isRotationOfPalindrome(inputStr4));
Outputtrue
true
false
false
Similar Reads
JavaScript Program to Check if an Array is Palindrome or Not
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if an array is a palindrome, compare it to its reverse version. If they match, it's a palindrome. Given an array, the task is to determine whether an array is a palindrome. Exam
3 min read
JavaScript Program to Check for Palindrome String using Recursion
Given a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. A string is called a palindrome if the reverse of the string is the same as the original one. For example - âmadamâ, âracecarâ, etc.What is Recursion?The process in which a function ca
3 min read
JavaScript Program to Check for Palindrome Number
We are going to learn about Palindrome Numbers in JavaScript. A palindrome number is a numerical sequence that reads the same forwards and backward, It remains unchanged even when reversed, retaining its original identity. Example: Input : Number = 121Output : PalindromeInput : Number = 1331Output :
4 min read
JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
We are given a matrix containing only lower-case alphabetical characters. The task is to print all the palindromic paths present in the given matrix. A path is a sequence of cells starting from the top-left cell and ending at the bottom-right cell. We are allowed to move only to the right and down f
4 min read
R Program to Check if a String is a Palindrome
In this article, we explore a simple yet essential task in programming: checking whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forwards and backwards, making it a common problem in text processing and string manipulation. We'll delve into the lo
5 min read
Javascript Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABAOutput : TrueInput : GEEKS, EKSGEOutput : TrueWe have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest
2 min read
How to check the given string is palindrome using JavaScript ?
A palindrome is a word, sentence, or even number that reads the same from the back and from the front. Therefore if we take the input, reverse the string and check if the reversed string and the original string are equal, it means the string is a palindrome, otherwise, it is not. Approach: When the
3 min read
Javascript Program to Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str
4 min read
Javascript Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string in two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwiseAsked in: Amazon Int
2 min read
Javascript Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1Output: YesAll rows are rotated permutationof each other.Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2Output: NoExplanation : As 3, 2, 1 is not
2 min read