![]() |
VOOZH | about |
Given two positive integers N, M. The task is to find the number of strings of length N under the alphabet set of size M such that no substrings of size greater than 1 is palindromic.
Examples:
Input : N = 2, M = 3
Output : 6
In this case, set of alphabet are 3, say {A, B, C}
All possible string of length 2, using 3 letters are:
{AA, AB, AC, BA, BB, BC, CA, CB, CC}
Out of these {AA, BB, CC} contain palindromic substring,
so our answer will be
8 - 2 = 6.
Input : N = 2, M = 2
Output : 2
Out of {AA, BB, AB, BA}, only {AB, BA} contain
non-palindromic substrings.
First, observe, a string does not contain any palindromic substring if the string doesn't have any palindromic substring of the length 2 and 3, because all the palindromic string of the greater lengths contains at least one palindromic substring of the length of 2 or 3, basically in the center.
So, the following is true:
Knowing this, we can evaluate the answer in the following ways:
Below is the implementation of above idea :
6
Time Complexity: O(log n), for using of pow function where n is the given input.
Auxiliary Space: O(1), no extra space is required, so it is a constant.