Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice - GeeksforGeeks

26 Aug, 2021
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.
Examples:
Input: N = 3, K = 2Output: 6Explanation:The possible strings are:“a”, “b”, “aa”, “bb”, “aba”, “bab”.
Input: N = 4, K = 3Output: 18Explanation: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.
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.
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:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function of return the number of// palindromic strings of length N with// first K alphabets possibleint lengthNPalindrome(int N, int K){    int half = N / 2;     // If N is odd, half + 1 position    // can be filled to cope with the    // extra middle element    if (N & 1) {        half += 1;    }     int ans = 1;    for (int i = 1; i <= half; i++) {        ans *= K;         // K is reduced by one, because        // count of choices for the next        // position is  reduced by 1 as        // a element can only once        K--;    }     // Return the possible count    return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriaint palindromicStrings(int N, int K){    // If N=1, then only K palindromic    // strings possible.    if (N == 1) {        return K;    }     // If N=2, the 2*K palindromic strings    // possible, K for N=1 and K for N=2    if (N == 2) {        return 2 * K;    }     int ans = 0;     // Initialize ans with the count of    // strings possible till N = 2    ans += (2 * K);     for (int i = 3; i <= N; i++) {        ans += lengthNPalindrome(i, K);    }     // Return the possible count    return ans;} // Driver Codeint main(){    int N = 4, K = 3;    cout << palindromicStrings(N, K);     return 0;}
// Java program for the above approachimport java.io.*; class GFG {    // Function of return the number of    // palindromic strings of length N with    // first K alphabets possible    static int lengthNPalindrome(int N, int K)    {        int half = N / 2;         // If N is odd, half + 1 position        // can be filled to cope with the        // extra middle element        if (N % 2 == 1) {            half += 1;        }         int ans = 1;        for (int i = 1; i <= half; i++) {            ans *= K;             // K is reduced by one, because            // count of choices for the next            // position is  reduced by 1 as            // a element can only once            K--;        }         // Return the possible count        return ans;    }     // Function to find the count of palindromic    // string of first K characters according    // to the given criteria    static int palindromicStrings(int N, int K)    {        // If N=1, then only K palindromic        // strings possible.        if (N == 1) {            return K;        }         // If N=2, the 2*K palindromic strings        // possible, K for N=1 and K for N=2        if (N == 2) {            return 2 * K;        }         int ans = 0;         // Initialize ans with the count of        // strings possible till N = 2        ans += (2 * K);         for (int i = 3; i <= N; i++) {            ans += lengthNPalindrome(i, K);        }         // Return the possible count        return ans;    }     // Driver Code    public static void main(String[] args)    {        int N = 4, K = 3;         System.out.println(palindromicStrings(N, K));    }}// This code is contributed by Potta Lokesh
# Python3 program for the above approach  # Function of return the number of# palindromic strings of length N with# first K alphabets possibledef lengthNPalindrome(N, K) :         half = N // 2;     # If N is odd, half + 1 position    # can be filled to cope with the    # extra middle element    if (N & 1) :        half += 1;     ans = 1;    for i in range(1, half + 1) :        ans *= K;         # K is reduced by one, because        # count of choices for the next        # position is  reduced by 1 as        # a element can only once        K -= 1;     # Return the possible count    return ans; # Function to find the count of palindromic# string of first K characters according# to the given criteriadef palindromicStrings(N, K) :     # If N=1, then only K palindromic    # strings possible.    if (N == 1) :        return K;     # If N=2, the 2*K palindromic strings    # possible, K for N=1 and K for N=2    if (N == 2) :        return 2 * K;     ans = 0;     # Initialize ans with the count of    # strings possible till N = 2    ans += (2 * K);     for i in range(3, N + 1) :        ans += lengthNPalindrome(i, K);     # Return the possible count    return ans; # Driver Codeif __name__ == "__main__" :     N = 4; K = 3;    print(palindromicStrings(N, K));     # This code is contributed by AnkThon
// C# program for the above approachusing System; class GFG{       // Function of return the number of    // palindromic strings of length N with    // first K alphabets possible    static int lengthNPalindrome(int N, int K)    {        int half = N / 2;         // If N is odd, half + 1 position        // can be filled to cope with the        // extra middle element        if (N % 2 == 1) {            half += 1;        }         int ans = 1;        for (int i = 1; i <= half; i++) {            ans *= K;             // K is reduced by one, because            // count of choices for the next            // position is  reduced by 1 as            // a element can only once            K--;        }         // Return the possible count        return ans;    }     // Function to find the count of palindromic    // string of first K characters according    // to the given criteria    static int palindromicStrings(int N, int K)    {        // If N=1, then only K palindromic        // strings possible.        if (N == 1) {            return K;        }         // If N=2, the 2*K palindromic strings        // possible, K for N=1 and K for N=2        if (N == 2) {            return 2 * K;        }         int ans = 0;         // Initialize ans with the count of        // strings possible till N = 2        ans += (2 * K);         for (int i = 3; i <= N; i++) {            ans += lengthNPalindrome(i, K);        }         // Return the possible count        return ans;    }     // Driver Code    public static void Main(String[] args)    {        int N = 4, K = 3;         Console.Write(palindromicStrings(N, K));    }} // This code is contributed by shivanisinghss2110
<script> // Javascript program for the above approach // Function of return the number of// palindromic strings of length N with// first K alphabets possiblefunction lengthNPalindrome(N,K){    var half = N / 2;     // If N is odd, half + 1 position    // can be filled to cope with the    // extra middle element    if (N & 1) {        half += 1;    }     var ans = 1;    var i;    for(i = 1; i <= half; i++) {        ans *= K;         // K is reduced by one, because        // count of choices for the next        // position is  reduced by 1 as        // a element can only once        K--;    }     // Return the possible count    return ans;} // Function to find the count of palindromic// string of first K characters according// to the given criteriafunction palindromicStrings(N, K){    // If N=1, then only K palindromic    // strings possible.    if (N == 1) {        return K;    }     // If N=2, the 2*K palindromic strings    // possible, K for N=1 and K for N=2    if (N == 2) {        return 2 * K;    }     ans = 0;     // Initialize ans with the count of    // strings possible till N = 2    ans += (2 * K);     for (i = 3; i <= N; i++) {        ans += lengthNPalindrome(i, K);    }     // Return the possible count    return ans;} // Driver Code    var N = 4, K = 3;    document.write(palindromicStrings(N, K)); // This code is contributed by ipg2016107.</script>
  
18
 
 
Time Complexity: O(N2)Auxiliary Space: O(1)
 
lokeshpotta20
shivanisinghss2110
ankthon
ipg2016107
palindrome
Combinatorial
Mathematical
Strings
Strings
Mathematical
Combinatorial
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinations with repetitions
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of at most X characters from a given array
Given number of matches played, find number of teams in tournament
Number of handshakes such that a person shakes hands only once
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays