- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

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

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

- Related Articles
- Python program to find N-sized substrings with K distinct characters
- Program to find maximize palindrome length from subsequences in Python
- Program to find the length of the longest, that can be made using given letters in Python
- Program to find length of longest chunked palindrome decomposition in Python
- Python program to find probability of getting letter 'a' in some letters and k sized combinations
- Python program to print palindrome triangle with n lines
- Program to find kth smallest n length lexicographically smallest string in python
- C++ program to find string with palindrome substring whose length is at most k
- Program to find length of longest word that can be formed from given letters in python
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Program to find length of longest valid parenthesis from given string in Python
- Python ā N sized substrings with K distinct characters
- Find the largest palindrome number made from the product of two n digit numbers in JavaScript
- Decrypt String from Alphabet to Integer Mapping in Python
- Program to print āNā alphabet using the number pattern from 1 to n in C++

Advertisements