Counting the number of palindromes that can be constructed from a string in JavaScript


We are required to write a JavaScript function that takes in a string of characters as the first argument, say str, and a number, say num, as the second argument.

The function should count the number of palindrome strings all exactly of length num can be constructed from the given string str. The function should then finally return the count.

For example −

If the input string and the number is −

const str = 'ij';
const num = 4;

Then the output should be −

const output = 4;

because those four possible palindrome strings are −

'iiii', 'jjjj', 'ijji', 'jiij'

Approach:

We will first count the number of unique letters in the given string using a hash set. If the length of the palindrome is an odd number, the middle character can have u choices where u is the count of unique characters in the string.

When num is even, we will have the following possibilities −

power(u, num/2)

And when num is odd, we need to multiply this number by u since we have u choices for that position.

Example

Following is the code −

const str = 'ij';
const num = 4;
const findValidPalindromes = (str = '', num = 1) => {
   const set = new Set();
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      set.add(el);
   };
   const u = set.size;
   if(num & 1){
      return Math.pow(u, num/2) * u;
   }else{
      return Math.pow(u, num/2);
   };
};
console.log(findValidPalindromes(str, num));

Output

Following is the console output −

4

Updated on: 23-Jan-2021

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements