Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice
Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn’t appear more than twice.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 3, K = 2
The possible strings are:
“a”, “b”, “aa”, “bb”, “aba”, “bab”.
Input: N = 4, K = 3
The possible strings are:
“a”, “b”, “c”, “aa”, “bb”, “cc”, “aba”, “aca”, “bab”, “bcb”, “cac”, “cbc”, “abba”, “acca”, “baab”, “bccb”, “caac”, “cbbc”.
Approach: The given problem can be solved based on the following observations:
- Let’s try to build a 4 digit palindrome(N = 4) with only the first 3 English letters(K = 3). So, the idea is to create an empty string ( _ _ _ _ ) and now to get a palindrome out of it, only the two digits in one in its one half can be filled because the other two would be decided on the basis of them, i.e., if first 2 places are chosen to fill with a character of choice the last two will be same to that so that the string should be a palindrome.
- Here in this case, if a is filled in first position and b in second then the only choice remaining for 3rd and 4th is to be filled with b and a respectively.
- So this means, to find the number of palindromic strings with length 4 (N = 4) with only the first 3 letters (K = 3), count all the combinations possible for the first 2 digits(= N/2) i.e., 3*2=6 (3 choices for the first position and 2 choices for the second).
- The above-explained case is for an even length string (N is even), and for an odd length string (N is odd), N/2 + 1 indexes can be filled.
Follow the steps below to solve the given problem:
- Fo finding the count palindromic strings of length at most N, then count palindromic strings of each length from 1 to N and then add them together.
- For the value of N as:
- If N is even, then find all combinations possible till N/2 because only half of the positions can be filled.
- If N is odd, then find all combinations possible till N/2 +1, and extra + 1 for the element as the middle element.
- Add all of them together and print the answer accordingly.
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(1)