Count alphanumeric palindromes of length N - GeeksforGeeks

26 Apr, 2021
Given a positive integer N, the task is to find the number of alphanumeric palindromic strings of length N. Since the count of such strings can be very large, print the answer modulo 109 + 7.
Examples:
Input: N = 2Output: 62Explanation: There are 26 palindromes of the form {“AA”, “BB”, ..., “ZZ”}, 26 palindromes of the form {“aa”, “bb”, ..., “cc”} and 10 palindromes of the form {“00”, “11”, ..., “99”}. Therefore, the total number of palindromic strings = 26 + 26 + 10 = 62.
Input: N = 3Output: 3844
Naive Approach: The simplest approach is to generate all possible alphanumeric strings of length N and for each string, check if it is a palindrome or not. Since, at each position, 62 characters can be placed in total. Hence, there are 62N possible strings. 
Time Complexity: O(N*62N)Auxiliary Space: O(N) 
Efficient Approach: To optimize the above approach, the idea is to use the property of palindrome. It can be observed that if the length of the string is even, then for each index i from 0 to N/2, characters at indices i and (N – 1 – i) are the same. Therefore, for each position from 0 to N/ 2 there are 62N/2 options. Similarly, if the length is odd, 62(N+1)/2 options are there. Hence, it can be said that, for some N, there are 62ceil(N/2) possible palindromic strings. Follow the steps below to solve the problem:
For the given value of N, calculate 62ceil(N/2) mod 109 + 7 using Modular Exponentiation.
Print 62ceil(N/2) mod 109 + 7 as the required answer.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to calculate// (x ^ y) mod pint power(int x, int y,          int p){  // Initialize result  int res = 1;   // Update x if it is more  // than or equal to p  x = x % p;   if (x == 0)    return 0;   while (y > 0)  {    // If y is odd, multiply    // x with result    if ((y & 1) == 1)      res = (res * x) % p;     // y must be even now    y = y >> 1;    x = (x * x) % p;  }   // Return the final  // result  return res;} // Driver Codeint main(){     // Given N  int N = 3;  int flag, k, m;   // Base Case  if((N == 1) ||     (N == 2))    cout << 62;   else    m = 1000000000 + 7;   // Check whether n  // is even or odd  if(N % 2 == 0)  {    k = N / 2;    flag = true;  }  else  {    k = (N - 1) / 2;    flag = false;  }  if(flag != 0)  {          // Function Call    int a = power(62,                  k, m);    cout << a;  }  else  {    // Function Call    int a = power(62,                  (k + 1), m);    cout << a;  }} // This code is contributed by sanjoy_62
// Java program for the// above approachimport java.util.*;class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x,                 int y, int p){  // Initialize result  int res = 1;   // Update x if it is more  // than or equal to p  x = x % p;   if (x == 0)    return 0;   while (y > 0)  {    // If y is odd, multiply    // x with result    if ((y & 1) == 1)      res = (res * x) % p;     // y must be even now    y = y >> 1;    x = (x * x) % p;  }   // Return the final  // result  return res;} // Driver Codepublic static void main(String[] args){  // Given N  int N = 3;  int flag, k, m =0;   // Base Case  if ((N == 1) || (N == 2))    System.out.print(62);  else    m = 1000000000 + 7;   // Check whether n  // is even or odd  if (N % 2 == 0)  {    k = N / 2;    flag = 1;  }  else  {    k = (N - 1) / 2;    flag = 0;  }     if (flag != 0)  {    // Function Call    int a = power(62, k, m);    System.out.print(a);  }  else  {    // Function Call    int a = power(62, (k + 1), m);    System.out.print(a);  }}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to calculate (x ^ y) mod pdef power(x, y, p):     # Initialize result    res = 1     # Update x if it is more    # than or equal to p    x = x % p     if (x == 0):        return 0     while (y > 0):         # If y is odd, multiply        # x with result        if ((y & 1) == 1):            res = (res * x) % p         # y must be even now        y = y >> 1        x = (x * x) % p     # Return the final result    return res  # Driver Code # Given NN = 3 # Base Caseif((N == 1) or (N == 2)):    print(62)     else:     m = (10**9)+7     # Check whether n    # is even or odd    if(N % 2 == 0):        k = N//2        flag = True    else:        k = (N - 1)//2        flag = False             if(flag):               # Function Call        a = power(62, k, m)        print(a)    else:         # Function Call        a = power(62, (k + 1), m)        print(a)
// C# program for the// above approachusing System; class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x, int y,                 int p){     // Initialize result  int res = 1;   // Update x if it is more  // than or equal to p  x = x % p;   if (x == 0)    return 0;   while (y > 0)  {         // If y is odd, multiply    // x with result    if ((y & 1) == 1)      res = (res * x) % p;     // y must be even now    y = y >> 1;    x = (x * x) % p;  }   // Return the final  // result  return res;} // Driver Codepublic static void Main(){     // Given N  int N = 3;  int flag, k, m = 0;   // Base Case  if ((N == 1) || (N == 2))    Console.Write(62);  else    m = 1000000000 + 7;   // Check whether n  // is even or odd  if (N % 2 == 0)  {    k = N / 2;    flag = 1;  }  else  {    k = (N - 1) / 2;    flag = 0;  }     if (flag != 0)  {    // Function Call    int a = power(62, k, m);    Console.Write(a);  }  else  {         // Function Call    int a = power(62, (k + 1), m);    Console.Write(a);  }}} // This code is contributed by code_hunt
<script> // JavaScript program to implement// the above approach // Function to calculate// (x ^ y) mod pfunction power(x, y, p){  // Initialize result  let res = 1;    // Update x if it is more  // than or equal to p  x = x % p;    if (x == 0)    return 0;    while (y > 0)  {    // If y is odd, multiply    // x with result    if ((y & 1) == 1)      res = (res * x) % p;      // y must be even now    y = y >> 1;    x = (x * x) % p;  }    // Return the final  // result  return res;}// Driver Code       // Given N  let N = 3;  let flag, k, m =0;    // Base Case  if ((N == 1) || (N == 2))    document.write(62);  else    m = 1000000000 + 7;    // Check whether n  // is even or odd  if (N % 2 == 0)  {    k = N / 2;    flag = 1;  }  else  {    k = (N - 1) / 2;    flag = 0;  }      if (flag != 0)  {    // Function Call    let a = power(62, k, m);    document.write(a);  }  else  {    // Function Call    let a = power(62, (k + 1), m);    document.write(a);  }           </script>
3844
 
Time Complexity: O(log N)Auxiliary Space: O(N)
sanjoy_62
29AjayKumar
code_hunt
splevel62
Modular Arithmetic
palindrome
permutation
Permutation and Combination
Combinatorial
Mathematical
Strings
Strings
Mathematical
permutation
Combinatorial
palindrome
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to get all subsets of given size of a set
Lexicographic rank of a string
Print all permutations in sorted (lexicographic) order
Print all subsets of given size of a set
Make all combinations of size k
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays