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.

Problem Example

If the input string and the number is:

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

Then the output should be:

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 middle position.

Solution

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){
        // For odd length palindromes
        return Math.pow(u, Math.floor(num/2)) * u;
    } else {
        // For even length palindromes
        return Math.pow(u, num/2);
    }
};

console.log(findValidPalindromes(str, num));

Output

4

How It Works

The algorithm works by recognizing that in a palindrome, characters must be mirrored. For a palindrome of length n, we only need to determine the first half of the characters (the rest are determined by symmetry). If we have u unique characters, we have u choices for each position in the first half.

For even-length palindromes: we need to fill num/2 positions, giving us u^(num/2) possibilities.

For odd-length palindromes: we fill (num-1)/2 positions for the first half, plus one middle character, giving us u^((num-1)/2) * u = u^(num/2) * u possibilities.

Conclusion

This solution efficiently counts palindromes by focusing on unique characters and the symmetric nature of palindromes. The time complexity is O(n) for counting unique characters, where n is the string length.

Updated on: 2026-03-15T23:19:00+05:30

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements