Program to find n length string made of letters from m sized alphabet with no palindrome in Python

PythonServer Side ProgrammingProgramming

Suppose we have m number of letters and another value n. We have to count number of strings of length n created with letters by taking from these m letters, and string has no palindromic substring of length greater than 1. If answer is too large then mod the result by 10^9+7.

So, if the input is like n = 2 m = 3, then the output will be 6 because m = 3, so if the alphabets are {x,y,z}, we can generate strings like: [xx,xy,xz,yx,yy,yz,zx,zy,zz] but [xx,yy,zz] are not valid so there are 6 strings.

To solve this, we will follow these steps −

  • p := 10^9+7
  • if n is same as 1, then
    • return m mod p
  • if n is same as 2, then
    • return m *(m - 1) mod p
  • if m <= 2, then
    • return 0
  • return m*(m-1) * ((m-2)^(n-2) mod p) mod p

Example

Let us see the following implementation to get better understanding −

def solve(n, m):
   p = 10**9+7
   if n == 1:
      return m % p
   if n == 2:
      return m * (m - 1) % p
   if m <= 2:
      return 0
   return m * (m - 1) * pow(m - 2, n - 2, p) % p

n = 2
m = 3
print(solve(n, m))

Input

3, [1,2,3,4,1]

Output

6
raja
Published on 25-Oct-2021 06:43:36

Advertisements