Given two integers N and K, the task is to find the count of palindromic strings of length lesser than or equal to N, with first K characters of lowercase English language, such that each character in a string doesn’t appear more than twice.
Note: Anwer can be very large, so, output answer modulo 10^{9}+7
Example 1:
Input: N = 3, K = 2
Output: 6
Explanation: The possible strings are:
"a", "b", "aa", "bb", "aba", "bab".
Example 2:
Input: N = 4, K = 3
Output: 18
Explanation: The possible strings are: 
"a", "b", "c", "aa", "bb", "cc", "aba",
"aca", "bab", "bcb", "cac", "cbc", 
"abba", "acca", "baab", "bccb", "caac", 
"cbbc". 
Your task:
You do not need to read any input or print anything. The task is to complete the function palindromicStrings(), which takes two integers as input and returns the count. 
Expected Time Complexity: O(K^{2})
Expected Auxiliary Space: O(K^{2})
Constraints:
1 ≤ K ≤ 26
1 ≤ N ≤ 52
N ≤ 2*K

Source: geeksforgeeks | Difficulty: MEDIUM
Tags: String algorithms

Combinatorics

Dynamic programming

Mathematics

Data structures

Starter code: #User function Template for python3
class Solution:
	def palindromicStrings(self, N, K ):
		# code here

Solutions:
def rec(N, K, dp):
	if N == 0:
		return 1
	if K == 0:
		return 0
	if N == 1:
		return K
	dp[N][K] = rec(N - 2, K - 1, dp) * K
	return dp[N][K]

class Solution:

	def palindromicStrings(self, N, K):
		mod = int(1000000000.0 + 7)
		dp = [[0 for i in range(K + 1)] for j in range(N + 1)]
		c = 0
		for i in range(1, N + 1):
			c += rec(i, K, dp)
		return c % mod


class Solution:

	def palindromicStrings(self, n, k):
		if n < 3:
			return k * n
		dp = [0 for i in range(n + 1)]
		dp[1] = dp[2] = k
		s = 2 * k
		for i in range(3, n + 1):
			v = (i - 1) // 2
			dp[i] = dp[i - 2] * (k - v) % 1000000007
			s += dp[i] % 1000000007
		return s % 1000000007


class Solution:

	def palindromicStrings(self, N, K):
		mod = 10 ** 9 + 7
		sumi = 0
		t = 1
		for i in range(1, N + 1):
			t = 1
			if i % 2 == 0:
				t2 = i // 2
			else:
				t2 = i // 2 + 1
			for j in range(t2):
				t *= K - j
				t %= mod
			sumi += t
			sumi %= mod
		return sumi


class Solution:

	def palindromicStrings(self, N, K):
		if N <= 1:
			return K
		dp = [0 for _ in range(N + 1)]
		mod = 10 ** 9 + 7
		dp[0] = 0
		dp[1] = K
		dp[2] = K
		for i in range(3, N + 1):
			p = (i - 1) // 2
			dp[i] = dp[i - 2] * (k - p) % mod
		Sum = 0
		for i in range(1, N + 1):
			Sum += dp[i] % mod
		return Sum % mod