How to use Character Frequency Count In Javascript
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:
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"));
Output
true true true false true
JavaScript Program to Check if a Given String is a Rotation of a Palindrome
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.
Table of Content
- Naive Approach
- Efficient Approach:
- Using Hashing