- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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'

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.

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));

Following is the console output −

4

- Related Questions & Answers
- Count occurrences of a string that can be constructed from another given string in C++
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Counting the number of redundant characters in a string - JavaScript
- Counting number of vowels in a string with JavaScript
- Number of letters in the counting JavaScript
- Counting substrings of a string that contains only one distinct letter in JavaScript
- Counting divisors of a number using JavaScript
- All possible strings of any length that can be formed from a given string?
- Can the string be segmented in JavaScript
- Program to check a string can be split into three palindromes or not in Python
- Counting number of words in a sentence in JavaScript
- Counting prime numbers from 2 upto the number n JavaScript
- Counting the number of 1s upto n in JavaScript
- Maximum Number of Events That Can Be Attended in C++
- Maximum number of candies that can be bought in C

Advertisements